Java中的输出重定向
如何在java中重定向输出 我正在eclipse中运行一个程序。我的代码如下:Java中的输出重定向,java,eclipse,Java,Eclipse,如何在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
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在这个输出中使用不同的颜色?调用
System.setOut()
重定向stdout,您需要调用重定向stderr-类似
// System.setOut(ps);
System.setErr(ps); // <-- for std err
//系统放样(ps);
系统设置错误(ps);// Eclipse控制台中的红色输出是打印到标准错误流(System.err
)上的文本。为了实现只将红色打印的文本写入文件,您需要替换对System.setOut(ps)的调用代码>与系统设置错误(ps)代码>
我怎样才能反其道而行之,在我的文件中打印红色文本而不是黑色文本
将输出从标准输出(System.out
)重定向到文件,而不是从错误流(System.err
)重定向输出。换句话说,不是
System.setOut(ps);
使用
为什么eclipse在这个输出中使用不同的颜色
因此,您可以看到哪个输出来自System.out
(黑色),哪个来自System.err
(红色-处理打印异常)
System.setErr(ps);
// ^^^