我有一个程序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。
发布于 2011-01-20 07:26:29
Runtime.exec的标准输出不会自动发送到调用方的标准输出。
类似这样的事情要做--访问派生进程的标准输出,读取它,然后将它写出来。请注意,派生流程的输出可用于使用流程实例的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) {
// ...
}
}发布于 2011-01-20 07:28:02
从JDK1.5开始,就有了java.lang.ProcessBuilder,它也可以处理std和err流。它可以说是java.lang.Runtime的替代品,你应该使用它。
发布于 2011-01-20 07:27:00
System.out不是您通过调用exec()产生的新进程的标准输出。如果您想查看"HelloWorld2“,则必须获取从exec()调用返回的进程,然后从中调用getOutputStream()。
https://stackoverflow.com/questions/4741878
复制相似问题