Home > Java > javaTutorial > How to Redirect Process Output Asynchronously in Java?

How to Redirect Process Output Asynchronously in Java?

Linda Hamilton
Release: 2024-11-18 08:20:02
Original
606 people have browsed it

How to Redirect Process Output Asynchronously in Java?

Asynchronous Output Redirection for ProcessBuilder

When executing processes in Java using ProcessBuilder, capturing stdout and stderr requires a non-blocking approach. While creating a thread to handle the redirection task is an option, it comes with drawbacks such as thread management and termination.

ProcessBuilder.inheritIO

In Java 7 and above, ProcessBuilder offers the inheritIO method. This method simplifies output redirection by setting the subprocess standard I/O to align with that of the current Java process.

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

This syntax seamlessly redirects both stdout and stderr to the console without blocking the main thread.

Java 6 and Earlier

For Java 6 and earlier versions, a more explicit solution is required:

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

In this implementation, new threads are spawned to continuously read from stdin and redirect its contents to the desired destination. When the subprocess finishes, the threads automatically terminate since the input stream reaches EOF.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template