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

2024-03-12

我有一个程序 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 的标准输出不会自动发送到调用者的标准输出。

像这样的事情要做 - 访问分叉进程的标准输出,读取它然后写出来。请注意,父进程可以使用分叉进程的输出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) {
       // ...
     }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 System.setOut() 重定向 Runtime.getRuntime().exec() 输出; 的相关文章

随机推荐