本文关键词:

java 标准输出与标准错误    out与 err 区别 用法 联系  java中的out与err区别  System.out和System.err的区别 System.out.println和System.err.println的区别 Java重定向System.out和System.err

概述

操作系统一般都有三个标准文件描述符:标准输入,标准输出,标准出错

这是操作系统的一种抽象表达

不同的语言需要有不同的具体表达方式,当然也不过是另一种包装抽象

比如c++的  cin cout cerr

Java中则是的System.in,System.out,System.err

示例

java 输出语句快捷键 java中输出语句_重定向

输出结果:

java 输出语句快捷键 java中输出语句_重定向

----------------

java 输出语句快捷键 java中输出语句_重定向

----------------

java 输出语句快捷键 java中输出语句_重定向

可以看得出来:

运行多次  err的打印信息位置是不固定的

JDK文档

/*** The "standard" output stream. This stream is already
* open and ready to accept output data. Typically this stream
* corresponds to display output or another output destination
* specified by the host environment or user.
* 
* For simple stand-alone Java applications, a typical way to write
* a line of output data is:
* 

 
  
* System.out.println(data)
* 
* 
* See the println methods in class PrintStream.
*
*@seejava.io.PrintStream#println()
*@seejava.io.PrintStream#println(boolean)
*@seejava.io.PrintStream#println(char)
*@seejava.io.PrintStream#println(char[])
*@seejava.io.PrintStream#println(double)
*@seejava.io.PrintStream#println(float)
*@seejava.io.PrintStream#println(int)
*@seejava.io.PrintStream#println(long)
*@seejava.io.PrintStream#println(java.lang.Object)
*@seejava.io.PrintStream#println(java.lang.String)*/
public static final PrintStream out = null;/*** The "standard" error output stream. This stream is already
* open and ready to accept output data.
* 
* Typically this stream corresponds to display output or another
* output destination specified by the host environment or user. By
* convention, this output stream is used to display error messages
* or other information that should come to the immediate attention
* of a user even if the principal output stream, the value of the
* variable out, has been redirected to a file or other
* destination that is typically not continuously monitored.*/
public static final PrintStream err = null;

是System 的两个内置变量   都是 PrintStream  类型的

out:

“标准”输出流。此流已打开并准备接受输出数据。

通常,此流对应于显示器输出或者由主机环境或用户指定的另一个输出目标。

err:

“标准”错误输出流。此流已打开并准备接受输出数据。

通常,此流对应于显示器输出或者由主机环境或用户指定的另一个输出目标。

按照惯例,此输出流用于显示错误消息

或者显示那些即使用户输出流(变量 out 的值)已经重定向到通常不被连续监视的某一文件或其他目标,也应该立刻引起用户注意的其他信息。

也就是说,out用于输出,err用于一切你认为逻辑上是错误的东西,需要引起注意的东西

差别

System.out在JVM和操作系统都具有缓存功能,

就是你输出的东西不一定实时输出,有时候会积攒到一定数量才会输出

System.err会实时输出(默认设置,可以改)

这也是为什么err打印位置不固定的原因

如果使用了log4j的日志记录,且设定错误等级的话  System.err会被记入日志,System.out不会

而且一般在IDE中使用err ,都会变色的比如eclipse中红色

System.setErr()System.setOut() 可以重定向这两个流

System.setOut(new PrintStream(new FileOutputStream(new File( "d://out.txt "))));
System.setErr(new PrintStream(new FileOutputStream(new File( "d://err.txt "))));

重定向后没有输出了

java 输出语句快捷键 java中输出语句_重定向