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

Java 使用System.setOut()重定向Runtime.getRuntime().exec()输出;,java,redirect,runtime,exec,runtime.exec,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

我有一个程序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

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

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


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

    类似这样的事情很难做到——访问forked进程的标准输出,读取它,然后写出它。请注意,使用流程实例的
    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) {
           // ...
         }
    }
    

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

    因为JDK 1.5有java.lang.ProcessBuilder,它也处理std和err流。它在某种程度上取代了java.lang.Runtime,您应该使用它。

    实现目标的更简单方法:

        ProcessBuilder builder = new ProcessBuilder("hostname");
        Process process = builder.start();
        Scanner in = new Scanner(process.getInputStream());
        System.out.println(in.nextLine()); // or use iterator for multilined output
    

    是否需要使用运行时?@Navi:有其他选择吗?!告诉我。我想知道!或者您的意思是使用ProcessBuilder