这可能是一个微不足道的问题,但我无法轻易找到答案。我有一个简单的 Java 程序:
System.setOut(new PrintStream(new File("stdout.txt")));
...
...
ProcessBuilder pb = new ProcessBuilder("... some args ...");
pb.inheritIO();
pb.start().waitFor();
我的目的是存储进程的所有输出(包括子进程)pb
) 在里面stdout.txt
。但是,这似乎不起作用,并且输出pb
被重定向到我的进程父级的标准输出,就像System.setOut(...)
从未被调用过。
有什么办法我可以使用pb.inheritIO/pb.inheritOutput
方法重定向到重定向 System.out
?我错过了一些明显的事情吗?我知道我能做到老办法通过在线程中手动读取孩子的标准输出,但这只会更麻烦。
干杯,
雅采克
请看我的回答https://stackoverflow.com/a/32342557/5226711 https://stackoverflow.com/a/32342557/5226711:
I/O 重定向ProcessBuilder
不重定向流,但
文件描述符。均匀设置System.out
到另一个流不
更改初始标准输出的文件描述符。ProcessBuilder.inheritIO()
继承父进程的标准
输出/输入/错误文件描述符。
The PrintStream
实例未传递到已启动的操作
系统进程,而是类似的东西(它是伪代码,我不
认为它确实有效):
((FileOutputStream) System.out.out).getFD()
或者,更正确的是:
FileDescriptor.out
这是static final
表明即使
你设置System.out
到不同的东西。
关于你的问题,这意味着你必须使用File
and ProcessBuilder.redirectOutput(File)
代替PrintStream
:
ProcessBuilder pb = new ProcessBuilder("... some args ...");
pb.redirectOutput(new File("stdout.txt"));
pb.start().waitFor();
这仅将子进程的输出重定向到 stdout.txt。
如果要定向父进程和子进程的所有输出,则必须将父进程的 System.out 重定向到该文件,并在父进程中捕获子进程的输出并将其输出到其重定向的 System.out:
System.setOut(new PrintStream(new File("stdout.txt")));
ProcessBuilder pb = new ProcessBuilder("... some args ...");
Process p = pb.start();
BufferedReader childOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = output.readLine()) != null) {
System.out.println(line); // child`s output goes to stdout.txt
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)