将进程重定向到stdout

Dón*_*nal 24 java groovy

我想在Groovy程序中执行foo.bat并将生成的进程'输出重定向到stdout.Java或Groovy代码示例都可以.

foo.bat可能需要几分钟才能运行并产生大量输出,因此我希望一旦生成就看到输出,而不是必须等到进程完成后才能立即看到所有输出.

Pan*_*til 55

使用inheritIO()方法将所有流重定向到标准输出很简单.这会将输出打印到运行此命令的进程的stdout.

ProcessBuilder pb = new ProcessBuilder("command", "argument");
pb.directory(new File(<directory from where you want to run the command>));
pb.inheritIO();
Process p = pb.start();
p.waitFor();
Run Code Online (Sandbox Code Playgroud)

还存在其他方法,如下所述.这些单独的方法将有助于仅重定向所需的流.

    pb.redirectInput(Redirect.INHERIT)
    pb.redirectOutput(Redirect.INHERIT)
    pb.redirectError(Redirect.INHERIT)
Run Code Online (Sandbox Code Playgroud)

  • 这是正确回答问题的答案。OP 询问如何重定向输出,而不是如何打印输出的每一行。非常重要的区别 (2认同)

jit*_*ter 33

这使用一个类来读取执行的程序生成的所有输出并将其显示在它自己的标准输出中.

class StreamGobbler extends Thread {
    InputStream is;

    // reads everything from is until empty. 
    StreamGobbler(InputStream is) {
        this.is = is;
    }

    public void run() {
        try {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
                System.out.println(line);    
        } catch (IOException ioe) {
            ioe.printStackTrace();  
        }
    }
}

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("javac");
//output both stdout and stderr data from proc to stdout of this process
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream());
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream());
errorGobbler.start();
outputGobbler.start();
proc.waitFor();
Run Code Online (Sandbox Code Playgroud)

  • 我的问题是,如果进程目前没有输出内容,循环将在进程完成之前结束,对吗? (2认同)

gMa*_*ale 7

如果您希望使用更多Groovy和更少的java来执行此操作,则会在发生时打印每一行:

def cmd = "./longRunningProcess"

def process = cmd.execute()
process.in.eachLine { line -> println line }
Run Code Online (Sandbox Code Playgroud)

或者,如果你想看到stdout和stderr

def cmd = "./longRunningProcess"

def process = cmd.execute()
process.waitForProcessOutput( System.out, System.err )
Run Code Online (Sandbox Code Playgroud)


Kei*_*all 5

如果您只是想获取简单命令的输出,这里有一些更简单的方法。如果您想并行处理或者您的命令采用 stdin 或生成 std​​err,则需要使用像 jitter 那样的线程。

如果您获得大量输出,请使用缓冲副本(如下所示) 。

import java.io.*;
public class test {
  static void copy(InputStream in, OutputStream out) throws IOException {
    while (true) {
      int c = in.read();
      if (c == -1) break;
      out.write((char)c);
    }
  }

  public static void main(String[] args) throws IOException, InterruptedException {
    String cmd = "echo foo";
    Process p = Runtime.getRuntime().exec(cmd);
    copy(p.getInputStream(), System.out);
    p.waitFor();
  }
}
Run Code Online (Sandbox Code Playgroud)