101

我正在使用 ProcessBuilder 在 Java 中构建一个流程,如下所示:

ProcessBuilder pb = new ProcessBuilder()
        .command("somecommand", "arg1", "arg2")
        .redirectErrorStream(true);
Process p = pb.start();

InputStream stdOut = p.getInputStream();

现在我的问题如下:我想捕获该进程的标准输出和/或标准错误,并将其重定向到System.out异步。我希望进程及其输出重定向在后台运行。到目前为止,我发现这样做的唯一方法是手动生成一个新线程,该线程将连续读取stdOut,然后write()调用System.out.

new Thread(new Runnable(){
    public void run(){
        byte[] buffer = new byte[8192];
        int len = -1;
        while((len = stdOut.read(buffer)) > 0){
            System.out.write(buffer, 0, len);
        }
    }
}).start();

虽然这种方法有效,但感觉有点脏。最重要的是,它为我提供了另一个线程来正确管理和终止。有没有更好的方法来做到这一点?

4

12 回答 12

162

使用ProcessBuilder.inheritIO,它将子进程标准 I/O 的源和目标设置为与当前 Java 进程的相同。

Process p = new ProcessBuilder().inheritIO().command("command1").start();

如果 Java 7 不是一个选项

public static void main(String[] args) throws Exception {
    Process p = Runtime.getRuntime().exec("cmd /c dir");
    inheritIO(p.getInputStream(), System.out);
    inheritIO(p.getErrorStream(), System.err);

}

private static void inheritIO(final InputStream src, final PrintStream dest) {
    new Thread(new Runnable() {
        public void run() {
            Scanner sc = new Scanner(src);
            while (sc.hasNextLine()) {
                dest.println(sc.nextLine());
            }
        }
    }).start();
}

当子进程完成时,线程将自动死亡,因为srcEOF 也会。

于 2013-01-05T02:54:23.117 回答
73

对于Java 7 及更高版本,请参阅 Evgeniy Dorofeev 的回答

对于Java 6 及更早版本,创建并使用StreamGobbler

StreamGobbler errorGobbler = 
  new StreamGobbler(p.getErrorStream(), "ERROR");

// any output?
StreamGobbler outputGobbler = 
  new StreamGobbler(p.getInputStream(), "OUTPUT");

// start gobblers
outputGobbler.start();
errorGobbler.start();

...

private class StreamGobbler extends Thread {
    InputStream is;
    String type;

    private StreamGobbler(InputStream is, String type) {
        this.is = is;
        this.type = type;
    }

    @Override
    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(type + "> " + line);
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
于 2013-01-04T21:50:57.223 回答
21

使用 Java 8 lambda 的灵活解决方案,可让您提供Consumer将逐行处理输出(例如记录它)的方法。run()是一个没有抛出检查异常的单行程序。作为实现的替代方案,它可以像其他答案所建议的那样Runnable进行扩展。Thread

class StreamGobbler implements Runnable {
    private InputStream inputStream;
    private Consumer<String> consumeInputLine;

    public StreamGobbler(InputStream inputStream, Consumer<String> consumeInputLine) {
        this.inputStream = inputStream;
        this.consumeInputLine = consumeInputLine;
    }

    public void run() {
        new BufferedReader(new InputStreamReader(inputStream)).lines().forEach(consumeInputLine);
    }
}

然后,您可以像这样使用它:

public void runProcessWithGobblers() throws IOException, InterruptedException {
    Process p = new ProcessBuilder("...").start();
    Logger logger = LoggerFactory.getLogger(getClass());

    StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), System.out::println);
    StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), logger::error);

    new Thread(outputGobbler).start();
    new Thread(errorGobbler).start();
    p.waitFor();
}

在这里,输出流被重定向到System.out,错误流由logger.

于 2015-10-28T08:59:06.927 回答
16

它很简单,如下所示:

    File logFile = new File(...);
    ProcessBuilder pb = new ProcessBuilder()
        .command("somecommand", "arg1", "arg2")
    processBuilder.redirectErrorStream(true);
    processBuilder.redirectOutput(logFile);

通过 .redirectErrorStream(true) 告诉进程合并错误和输出流,然后通过 .redirectOutput(file) 将合并的输出重定向到文件。

更新:

我确实设法做到了如下:

public static void main(String[] args) {
    // Async part
    Runnable r = () -> {
        ProcessBuilder pb = new ProcessBuilder().command("...");
        // Merge System.err and System.out
        pb.redirectErrorStream(true);
        // Inherit System.out as redirect output stream
        pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        try {
            pb.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };
    new Thread(r, "asyncOut").start();
    // here goes your main part
}

现在您可以在System.out中看到 main 和 asyncOut 线程的输出

于 2016-11-08T11:20:39.490 回答
4

使用以下方法捕获输出和反应式处理的简单 java8 解决方案CompletableFuture

static CompletableFuture<String> readOutStream(InputStream is) {
    return CompletableFuture.supplyAsync(() -> {
        try (
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
        ) {
              StringBuilder res = new StringBuilder();
              String inputLine;
              while ((inputLine = br.readLine()) != null) {
                  res.append(inputLine).append(System.lineSeparator());
              }
              return res.toString();
        } catch (Throwable e) {
            throw new RuntimeException("problem with executing program", e);
        }
    });
}

以及用法:

Process p = Runtime.getRuntime().exec(cmd);
CompletableFuture<String> soutFut = readOutStream(p.getInputStream());
CompletableFuture<String> serrFut = readOutStream(p.getErrorStream());
CompletableFuture<String> resultFut = 
    soutFut.thenCombine(serrFut, (stdout, stderr) -> {
         // print to current stderr the stderr of process and return the stdout
         System.err.println(stderr);
        
         return stdout;
    });
// get stdout once ready, blocking
String result = resultFut.get();
于 2019-08-13T18:45:54.277 回答
4

有一个库提供了更好的 ProcessBuilder,zt-exec。该库可以完全满足您的要求以及更多功能。

这是使用 zt-exec 而不是 ProcessBuilder 时您的代码的样子:

添加依赖项:

<dependency>
  <groupId>org.zeroturnaround</groupId>
  <artifactId>zt-exec</artifactId>
  <version>1.11</version>
</dependency>

编码 :

new ProcessExecutor()
  .command("somecommand", "arg1", "arg2")
  .redirectOutput(System.out)
  .redirectError(System.err)
  .execute();

该库的文档在这里:https ://github.com/zeroturnaround/zt-exec/

于 2020-04-20T09:08:50.243 回答
3

我也只能使用 Java 6。我使用了 @EvgeniyDorofeev 的线程扫描器实现。在我的代码中,一个进程完成后,我必须立即执行另外两个进程,每个进程都比较重定向的输出(基于差异的单元测试,以确保 stdout 和 stderr 与祝福的相同)。

即使我 waitFor() 进程完成,扫描程序线程也不会很快完成。为了使代码正常工作,我必须确保在进程完成后加入线程。

public static int runRedirect (String[] args, String stdout_redirect_to, String stderr_redirect_to) throws IOException, InterruptedException {
    ProcessBuilder b = new ProcessBuilder().command(args);
    Process p = b.start();
    Thread ot = null;
    PrintStream out = null;
    if (stdout_redirect_to != null) {
        out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdout_redirect_to)));
        ot = inheritIO(p.getInputStream(), out);
        ot.start();
    }
    Thread et = null;
    PrintStream err = null;
    if (stderr_redirect_to != null) {
        err = new PrintStream(new BufferedOutputStream(new FileOutputStream(stderr_redirect_to)));
        et = inheritIO(p.getErrorStream(), err);
        et.start();
    }
    p.waitFor();    // ensure the process finishes before proceeding
    if (ot != null)
        ot.join();  // ensure the thread finishes before proceeding
    if (et != null)
        et.join();  // ensure the thread finishes before proceeding
    int rc = p.exitValue();
    return rc;
}

private static Thread inheritIO (final InputStream src, final PrintStream dest) {
    return new Thread(new Runnable() {
        public void run() {
            Scanner sc = new Scanner(src);
            while (sc.hasNextLine())
                dest.println(sc.nextLine());
            dest.flush();
        }
    });
}
于 2014-02-07T19:31:25.370 回答
1

作为 msangel答案的补充,我想添加以下代码块:

private static CompletableFuture<Boolean> redirectToLogger(final InputStream inputStream, final Consumer<String> logLineConsumer) {
        return CompletableFuture.supplyAsync(() -> {
            try (
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            ) {
                String line = null;
                while((line = bufferedReader.readLine()) != null) {
                    logLineConsumer.accept(line);
                }
                return true;
            } catch (IOException e) {
                return false;
            }
        });
    }

它允许将进程的输入流(stdout、stderr)重定向到其他消费者。这可能是 System.out::println 或其他任何使用字符串的东西。

用法:

...
Process process = processBuilder.start()
CompletableFuture<Boolean> stdOutRes = redirectToLogger(process.getInputStream(), System.out::println);
CompletableFuture<Boolean> stdErrRes = redirectToLogger(process.getErrorStream(), System.out::println);
System.out.println(stdOutRes.get());
System.out.println(stdErrRes.get());
System.out.println(process.waitFor());
于 2020-03-06T10:21:50.750 回答
1

令我感到惊讶的是,重定向方法ProcessBuilder不接受OutputStream, only File。Java 强制您编写的强制样板代码的另一个证明。

也就是说,让我们看一下综合选项列表:

  1. 如果您希望将流程输出简单地重定向到其父级的输出流,inheritIO则可以完成这项工作。
  2. 如果您希望进程输出转到文件,请使用redirect*(file).
  3. 如果您希望进程输出转到记录器,则需要InputStream在单独的线程中使用该进程。查看使用 aRunnable或的答案CompletableFuture。您还可以调整下面的代码来执行此操作。
  4. 如果您想将流程输出转到一个PrintWriter,它可能是也可能不是标准输出(对测试非常有用),您可以执行以下操作:
static int execute(List<String> args, PrintWriter out) {
    ProcessBuilder builder = new ProcessBuilder()
            .command(args)
            .redirectErrorStream(true);
    Process process = null;
    boolean complete = false;
    try {
        process = builder.start();
        redirectOut(process.getInputStream(), out)
                .orTimeout(TIMEOUT, TimeUnit.SECONDS);
        complete = process.waitFor(TIMEOUT, TimeUnit.SECONDS);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (InterruptedException e) {
        LOG.warn("Thread was interrupted", e);
    } finally {
        if (process != null && !complete) {
            LOG.warn("Process {} didn't finish within {} seconds", args.get(0), TIMEOUT);
            process = process.destroyForcibly();
        }
    }

    return process != null ? process.exitValue() : 1;
}

private static CompletableFuture<Void> redirectOut(InputStream in, PrintWriter out) {
    return CompletableFuture.runAsync(() -> {
        try (
                InputStreamReader inputStreamReader = new InputStreamReader(in);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
        ) {
            bufferedReader.lines()
                    .forEach(out::println);
        } catch (IOException e) {
            LOG.error("Failed to redirect process output", e);
        }
    });
}

到目前为止,上述代码相对于其他答案的优势:

  1. redirectErrorStream(true)将错误流重定向到输出流,这样我们只需要处理一个即可。
  2. CompletableFuture.runAsyncForkJoinPool. 请注意,此代码不会通过调用getjoin在上阻塞,CompletableFuture而是在完成时设置超时(Java 9+)。没有必要,CompletableFuture.supplyAsync因为没有什么可以从 method 中返回redirectOut
  3. BufferedReader.lines比使用while循环更简单。
于 2021-01-10T02:44:02.810 回答
0
Thread thread = new Thread(() -> {
      new BufferedReader(
          new InputStreamReader(inputStream, 
                                StandardCharsets.UTF_8))
              .lines().forEach(...);
    });
    thread.start();

您的自定义代码代替...

于 2018-03-29T07:05:32.377 回答
-1
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws Exception {
        ProcessBuilder pb = new ProcessBuilder("script.bat");
        pb.redirectErrorStream(true);
        Process p = pb.start();
        BufferedReader logReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String logLine = null;
        while ( (logLine = logReader.readLine()) != null) {
           System.out.println("Script output: " + logLine);
        }
    }
}

通过使用这一行:pb.redirectErrorStream(true);我们可以结合 InputStream 和 ErrorStream

于 2020-10-26T18:46:30.340 回答
-2

默认情况下,创建的子进程没有自己的终端或控制台。它的所有标准I/O(即stdin、stdout、stderr)操作都将被重定向到父进程,在那里可以通过使用getOutputStream()、getInputStream() 和getErrorStream() 方法获得的流来访问它们。父进程使用这些流向子进程提供输入并从子进程获取输出。由于部分原生平台只为标准输入输出流提供有限的缓冲区大小,未能及时写入子进程的输入流或读取输出流可能会导致子进程阻塞,甚至死锁。

https://www.securecoding.cert.org/confluence/display/java/FIO07-J.+Do+not+let+external+processes+block+on+IO+buffers

于 2015-10-01T17:21:43.393 回答