While running an external script, I want to read the ErrorStream and OutputStream of this script both simultaneously and separately and then process them further. Therefore, I start a Thread
for one of the streams. Unfortunately, the Process
doesn't seem to waitFor
the Thread
to be terminated, but return after the non-threaded stream has no further input.
In a nutshell, here is what I am doing:
ProcessBuilder pb = new ProcessBuilder(script);
final Process p = pb.start();
new Thread(new Runnable() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
...read lines and process them...
}
}).start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
...read lines and process them...
int exitValue = p.waitFor();
p.getOutputStream().close();
return exitValue;
Is there any possibility to waitFor
the Thread
to be terminated?
Here's general code for doing what you want to do. In this case there is both input and output: I am piping
someFile
into the process and piping the output toSystem.out
.Files.copy()
andByteStreams.copy()
are just Guava convenience methods to hook up anInputStream
to anOutputStream
. We then wait for the command to finish.A more verbose version if you are running prior to Java 7 with the try-with-resources block:
You can use
Thread.join(...)
to wait for aThread
to finish. Note that the call throwsInterruptedException
if the current thread receives an interrupt before the thread you are waiting for finishes.