Search code examples
javaajaxasynchronousstrutsruntime.exec

Java Runtime.exec() asynchronous output


I'd like to get the output from a long running shell command as it is available instead of waiting for the command to complete. My code is run in a new thread

Process proc = Runtime.getRuntime().exec("/opt/bin/longRunning");
InputStream in = proc.getInputStream();
int c;
while((c = in.read()) != -1) {
    MyStaticClass.stringBuilder.append(c);
}

The problem with this is that my program in /opt/bin/longRunning has to complete before the InputStream gets assigned and read. Is there any good way to do this asynchronously? My goal is that an ajax request will return the current value MyStaticClass.stringBuilder.toString() every second or so.

I'm stuck on Java 5, fyi.

Thanks! W


Solution

  • Try with Apache Common Exec. It has the ability to asynchronously execute a process and then "pump" the output to a thread. Check the Javadoc for more info