使用System.setOut()重定向Runtime.getRuntime()。exec();

我有一个程序Test.java:

import java.io.*; public class Test { public static void main(String[] args) throws Exception { System.setOut(new PrintStream(new FileOutputStream("test.txt"))); System.out.println("HelloWorld1"); Runtime.getRuntime().exec("echo HelloWorld2"); } } 

这应该将HelloWorld1和HelloWorld2打印到文件text.txt。 但是,当我查看文件时,我只看到HelloWorld1。

  1. HelloWorld2去了哪里? 它消失在空气中吗?

  2. 假设我想将HelloWorld2重定向到test.txt。 我不能在命令中添加“>> test.txt”,因为我会得到一个文件已经打开错误。 那我该怎么做?

Runtime.exec的标准输出不会自动发送到调用者的标准输出。

这样的事情要做 – 可以访问分叉进程的标准输出,读取它然后写出来。 请注意,分叉进程的输出可以使用Process实例的getInputStream()方法提供给父进程。

 public static void main(String[] args) throws Exception { System.setOut(new PrintStream(new FileOutputStream("test.txt"))); System.out.println("HelloWorld1"); try { String line; Process p = Runtime.getRuntime().exec( "echo HelloWorld2" ); BufferedReader in = new BufferedReader( new InputStreamReader(p.getInputStream()) ); while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); } catch (Exception e) { // ... } } 

从JDK 1.5开始,java.lang.ProcessBuilder也处理std和err流。 它是java.lang.Runtime的替代品,你应该使用它。

System.out不是您通过调用exec()生成的新进程的标准输出。 如果你想看到“HelloWorld2”,你必须从exec()调用返回进程,然后从中调用getOutputStream()。