开发者

Java Runtime.exec() asynchronous output

I'd like to get the output from a long running shell command as it开发者_如何学JAVA 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


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


Runtime.getRuntime().exec does not wait for the command to terminate, so you should be getting the output straight away. Maybe the output is being buffered because the command knows it is writing to a pipe rather than a terminal?


Put the reading in a new thread:

new Thread() {
    public void run() {
        InputStream in = proc.getInputStream();
        int c;
        while((c = in.read()) != -1) {
            MyStaticClass.stringBuilder.append(c);
        }
    }
}.start();


Did you write the program you're calling? If so try flushing your output after writing. The text could be stuck in a buffer and not getting to your java program.

I use this code to do this and it works:

    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec(command);
    BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    while (true) {

        // enter a loop where we read what the program has to say and wait for it to finish
        // read all the program has to say
        while (br.ready()) {
            String line = br.readLine();
            System.out.println("CMD: " + line);
        }

        try {
            int exitCode = proc.exitValue();
            System.out.println("exit code: " + exitCode);
            // if we get here then the process finished executing
            break;
        } catch (IllegalThreadStateException ex) {
            // ignore
        }

        // wait 200ms and try again
        Thread.sleep(200);

    }


Try :

   try {  
         Process p = Runtime.getRuntime().exec("/opt/bin/longRunning");  
         BufferedReader in = new BufferedReader(  
                                    new InputStreamReader(p.getInputStream()));  
         String line = null;  
         while ((line = in.readLine()) != null) {  
         System.out.println(line);  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜