out与err输出流

System.in、System.out与System.err

当我们查阅文档可知,out与err都是Java中的输出流,in是”标准”输入流,System.out是”标准”输出流,而System.err是”标准”错误输出流。

out与err输出流

输入流

在学习Scanner用户交互时就有用到System.in,来获取用户的输入

Scanner s = new Scanner(System.in);

它的作用是为Scanner对象提供输入源,完成与用户的交互。

输出流

out与err都可以在控制台中作输出

先看一下他们的Demo

public static void main(String[] args) throws InterruptedException{
    SimpleDateFormat ss = new SimpleDateFormat("SS");
    System.err.println("err"+ss.format(System.currentTimeMillis()));
    for (int i = 1; i < 1200; i++) {
        System.out.println(ss.format(System.currentTimeMillis()));
        if (i % 3 == 0) System.err.println("err"+ss.format(System.currentTimeMillis()));
    }
    System.err.println("err"+ss.format(System.currentTimeMillis()));
}
/*第一次输出
err939
err940
err940
err940
err940
....

952
952
952
952
952
952
952
952

Process finished with exit code 0
*/

/*第n次输出
335
335
335
335
335
336
336
336
336
...

err335
err335
err335
err336
err336

Process finished with exit code 0
*/

在上次的两次输出会与程序中的顺序位置有所不同,err的输出不是在out前就是在out后,而且err输出的字体是红色的。

这是因为out有 缓存机制的,它的输出是由JVM和操作系统共同决定的,这会导致JVM在输出数据时,操作系统不同意在这个时间输出,它将保持等待状态直到将要输出的东西 达到一定的量。而err是 实时输出

如果我们想反映程序是否正常时,out的输出流可能会成问题。当我们有个程序是反映循环的,在循环到第100次时报错,但程序在输出第89次时就终止了,此时报错的循环层还在缓存中,无法给我们反馈正确的信息。而err输出流则会避免出现这些的问题,因为它是实时输出的,每循环一次就输出一次。

所以,关于输出程序报错或记录日志的,尽量使用err来输出

Original: https://www.cnblogs.com/hello12153-java/p/15978200.html
Author: hello_12153_98
Title: out与err输出流

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/570482/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球