Home  >  Article  >  Java  >  How to Redirect Subprocess Output Asynchronously in Java Without Blocking the Main Thread?

How to Redirect Subprocess Output Asynchronously in Java Without Blocking the Main Thread?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 04:02:02587browse

How to Redirect Subprocess Output Asynchronously in Java Without Blocking the Main Thread?

Redirecting Process Output Without Blocking the Main Thread

Question

In a Java application, how can one capture the stdout and stderr output of a subprocess launched using ProcessBuilder and redirect it to System.out asynchronously, allowing the subprocess and output redirection to run in the background?

The current approach involves manually creating a new thread to continuously read from stdout and write to System.out, but it feels cumbersome and requires additional thread management. Is there a more elegant solution?

Answer

By leveraging ProcessBuilder.inheritIO, you can set the subprocess's standard I/O to mirror that of the current Java process. This redirects the subprocess's output directly to System.out without requiring a separate thread.

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

If using Java 7 is not feasible, another option is to manually redirect using threads:

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();
}

This approach utilizes threads that automatically terminate when the subprocess completes, as the input/error streams reach their end.

The above is the detailed content of How to Redirect Subprocess Output Asynchronously in Java Without Blocking the Main Thread?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn