如何在 java 中重定向输出?
我正在 eclipse 中运行一个程序。我的代码如下:
public static void main(String[] args) throws Exception{
/* Redirect output to file */
File file = new File("fileName");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
OtherClass.main(args);
}
如果没有我上面写的输出重定向,代码返回一些黑色的值和一些红色的值(这不是错误,而是在 OtherClass 中调用的参数)。
上面的重定向将在 eclipse 控制台中以黑色显示的文本写入我的文件中,但 read 中的输出写入控制台而不是我的文件中。
我如何做相反的事情并在我的文件中打印红色文本而不是黑色文本?为什么 Eclipse 对此输出使用不同的颜色?
最佳答案
How can I do the contrary and print the red text in my file and not the black one?
不是将输出从标准输出 (System.out
) 重定向到文件,而是从错误流 (System.err
) 重定向输出。换句话说,而不是
System.setOut(ps);
使用
System.setErr(ps);
// ^^^
And why does eclipse use different colors for this output?
因此您可以看到哪些输出来自 System.out
(黑色),哪些来自 System.err
(红色 - 处理打印异常)。
关于java - Java 中的输出重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26152515/