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