Runtime currentRuntime = Runtime.getRuntime(); Process process = currentRuntime.exec(); // always handle the process output/error streams (java uses a small // buffer to read the output of a process; if this buffer gets // filled, the process waitFor() hangs) // catch any potential error message from the process StreamConsumer errorConsumer = new StreamConsumer(process.getErrorStream(), OutputType.ERR); // catch any potential output StreamConsumer outputConsumer = new StreamConsumer(process.getInputStream(), OutputType.OUT); // start consuming... errorConsumer.start(); outputConsumer.start(); int exitValue = process.waitFor(); // assume everything is okay... assert exitValue == 0 : "Process returned " + exitValue;
And the code for StreamConsumer
static class StreamConsumer extends Thread {
InputStream is;
OutputType type;
StreamConsumer(InputStream is, OutputType type) {
this.is = is;
this.type = type;
}
@Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
switch (type) {
case ERR:
System.err.println(line);
break;
case OUT:
System.out.println(line);
break;
default:
assert false : type;
break;
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}