开发者

To print output of a program Simultaneously as it runs

开发者 https://www.devze.com 2023-01-11 13:01 出处:网络
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 comp

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


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

0

精彩评论

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