Java输出控制台错误消息到文件?

我有一段简单的代码将控制台文本输出到Java中的文本文件:

PrintStream out = new PrintStream(new FileOutputStream("test2_output.txt")); System.setOut(out); 

但是,我要求此文本文件包含在控制台中生成的错误消息,但不包括它们。

我该怎么做呢?

加:

 System.setErr(out); 

最后。

还有一个System.setErr()调用来重定向stderr。

System.setErr(out)

您当前正在将标准输出流重定向到文件。 要重定向标准错误流,请使用

 System.setErr(out); 
  • System.setErr() javadoc

尝试:

 PrintStream pst = new PrintStream("Text.txt"); System.setOut(pst); System.setErr(pst); System.out.println("Hello, Finally I've printed output to file..");