tags:

views:

44

answers:

1

Guys,

In the following code, am executing a java program Newsworthy_CA. The program prints the output of the Newsworthy_CA program but the difficulty I face is it prints the whole output only after the complete execution of Newsworthy_CA program. But I need the output to be printed simultaneously as the program is being executed.

Also, I need child.waitFor() for stopping the program from continuation if any error occurs.

Please suggest me some good idea for my requirement. Thanks in advance.

Note: Am a beginner in Java

    command = "java Newsworthy_CA";
    Process child4 = Runtime.getRuntime().exec(command);
    try{
    c= child4.waitFor();
    } catch (Exception ex){ex.printStackTrace();}
    if (c!=0){
    System.out.println("Error Occurred in ("+command+"): "+c);
    InputStream in4 = child4.getErrorStream();
    while ((c = in4.read()) != -1) {
        System.out.print((char)c);
    }
    in4.close();
    return;
    }
    InputStream in4 = child4.getInputStream();
    while ((c = in4.read()) != -1) {
    System.out.print((char)c);
    }
    in4.close();
+1  A: 

If you want to see output from the external program as it executes, don't you want to have the the InputStream block moved up above the waitFor()?

As your code reads, you very clearly say to execute and wait for completion before doing anything... including printing the external program's output (the InputStream block).

RonU
yes... but I would like to know whether waitFor() will funcion as usual if I do as you have stated....?
LGAP
As the javadoc for waitFor() says, it will wait for the Process object to terminate, if necessary, before proceeding.So yes, you can execute other code in parallel (your stated objective), and if the Process is not finished by the time you get to waitFor(), it will then wait.Incidentally, you're almost certain for the Process to be finished since you're waiting on the termination of the standard out stream from the Process anyway. I.e., without an error condition, you'll be in the while(in4.read()) loop until the process terminates anyway.
RonU