Wednesday, April 8, 2009

Process.getInputStream()

The concept of an InputStream always refers to data coming IN to the thread which is invoking the InputStream method. Similarly, an OutputStream always refers to data pushed OUT by the thread which is invoking the OutputStream method.

The only place where this is really tricky is when you are working with Process objects. The getInputStream() method of Process returns a Java InputStream that reads from the standard output stream of the running Process.

The key thing to remember when using Runtime.exec() is you must consume everything from the child process' input stream. Otherwise, the child process may hang due to the buffer filling up.


Process proc = Runtime.getRuntime().exec(cmd);

StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream());
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream());
errorGobbler.start();
outputGobbler.start();

if (proc.waitFor() != 0) {
System.out.println("RestoreMain: Migration failed.");
result = false;
}


StreamGobbler

public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
// ------------------------------------------------------------
// Exhaust Stream
// ------------------------------------------------------------
log.debug("StreamGobbler: " + line);
}
} catch (Exception e) {
log.debug("Failed to exhaust stream.");
}
}

No comments: