System.out.println与System.err.println的区别(输出顺序!!!)

时间:2023-03-09 04:06:33
System.out.println与System.err.println的区别(输出顺序!!!)

System.out.println与System.err.println的区别(输出顺序!!!)

分类:java

(208)  (0)

System.out.println与System.err.println的区别(输出顺序!!!)

今天看到网上别人写的代码中有一行System.err.println用来输出,以前从没用过,今天一用出了很多问题,总结如下:

  • err是运行期异常和错误反馈的输出流的方向
  • System.err.println只能在屏幕上实现打印,即使你重定向了也一样
  • 用err打印出的 字符串,再eclipse的console会显示成红色
  • 标准输出往往是带缓存的,而标准出错没有缓存(默认设置,可以改)

参看以下代码了解

下面输出顺序如何?


1. public class TestCodeSeg
2. {
3. static
4. {
5. System.out.println("1");
6. }
7. {
8. System.out.println("2");
9. }
10. public TestCodeSeg()
11. {
12. System.err.println("3");
13. }
14. public static void main(String[] args)
15. {
16. new TestCodeSeg();
17. }
18. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

结果:1,2顺序不变,3输出不定位置不定。

原因:System.out.println输出有缓存,System.err.println是立即输出,可能在输出1或2,还没有输出换行时输出3。