【问题标题】:Redirect Runtime.getRuntime().exec() output with System.setOut();使用 System.setOut() 重定向 Runtime.getRuntime().exec() 输出;
【发布时间】:2011-06-12 03:06:26
【问题描述】:

我有一个程序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?
  • @Navi:还有其他选择吗?!告诉。我想知道!还是您的意思是使用 ProcessBuilder

标签: java redirect runtime exec runtime.exec


【解决方案1】:

实现目标的更简单方法:

    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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        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) {
               // ...
             }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-12-09
          • 1970-01-01
          • 1970-01-01
          • 2011-01-09
          • 2015-08-28
          • 2012-09-08
          • 1970-01-01
          • 2012-06-21
          相关资源
          最近更新 更多