Home > Java > javaTutorial > How to Efficiently Redirect ProcessBuilder Output Asynchronously in Java?

How to Efficiently Redirect ProcessBuilder Output Asynchronously in Java?

DDD
Release: 2024-11-23 20:38:11
Original
709 people have browsed it

How to Efficiently Redirect ProcessBuilder Output Asynchronously in Java?

Asynchronous Output Redirection for ProcessBuilder Processes

When constructing a process with ProcessBuilder, it can be desirable to capture and redirect stdout and/or stderr to System.out asynchronously. Traditional approaches, such as manually spawning a thread to continuously read from stdOut, are cumbersome and inefficient.

Fortunately, Java 7 introduced the ProcessBuilder.inheritIO method, which conveniently sets the subprocess standard I/O to be the same as the current Java process. This eliminates the need for additional threads or complex output redirection logic.

For Java 7 and later, simply invoke:

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

For earlier versions of Java, a custom 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 custom solution, threads are automatically terminated when the subprocess finishes, as the src stream reaches EOF. This ensures proper resource management without the need for explicit thread handling.

The above is the detailed content of How to Efficiently Redirect ProcessBuilder 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template