Java Asynchronous Runtime.exec () Output

I would like to get the result from the long running shell command, because it is available, not waiting for the command to complete. My code runs 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 is that my program in / opt / bin / longRunning must exit before the InputStream is assigned and read. Is there a good way to do this asynchronously? My goal is that the ajax request will return the current value of MyStaticClass.stringBuilder.toString () every second or so.

I am stuck on Java 5, fyi.

Thank! Tue

+6
source share
5 answers
+7

Runtime.getRuntime().exec , . , , , , ?

+2

:

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

, ? , . java-.

, :

    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);

    }
+1

:

   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

All Articles