Leo*_*zen 23 java redirect runtime exec runtime.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");
}
}
Run Code Online (Sandbox Code Playgroud)
这应该将HelloWorld1和HelloWorld2打印到文件text.txt.但是,当我查看文件时,我只看到HelloWorld1.
HelloWorld2去了哪里?它消失在空气中吗?
假设我想将HelloWorld2重定向到test.txt.我不能在命令中添加">> test.txt",因为我将得到一个文件已经打开错误.那我该怎么做?
mar*_*ton 39
Runtime.exec的标准输出不会自动发送到调用者的标准输出.
这样的事情要做 - 可以访问分叉进程的标准输出,读取它然后写出来.请注意,分叉进程的输出可以使用getInputStream()Process实例的方法提供给父进程.
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) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43612 次 |
| 最近记录: |