how to get stdout and stderr in Runtime.exec in real-time?

半世苍凉 提交于 2019-12-13 05:42:27

问题


I have following code:

 Process runJob = null;
    try {
        runJob = Runtime.getRuntime().exec(args);

    InputStream cmdStdErr = null;
    InputStream cmdStdOut = null;

    cmdStdErr = runJob.getErrorStream();
    cmdStdOut = runJob.getInputStream();


    String line;
    BufferedReader stdOut = new BufferedReader (new InputStreamReader (cmdStdOut));
    while ((line = stdOut.readLine ()) != null) {
        logger.info(line);

    }

    cmdStdOut.close();

    // send error to Ab Initio and exit
    BufferedReader br = new BufferedReader(new InputStreamReader(cmdStdErr));
    String errMsg="";
    while ((line = br.readLine()) != null) {
        logger.info(line);
        errMsg += line;

    }
    cmdStdErr.close();

    res = runJob.waitFor();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

The problem is that when the job is running it produces lot of output but inputstream for stdout and stderr print the output only after job is done.

Is there a way to get that output in realtime i.e. get the stderr and stdout as the job is outputting them ?

Thanks, JJ


回答1:


You're trying to read all of stdout - which will basically block until the process finishes - and then all of stderr.

Use two threads, one reading from stdout and one reading from stderr - that way it doesn't matter which of them "next" has data, you'll be reading from both of them.




回答2:


Don't use those BufferedReaders; they're buffering the data (of course) which means storing it up and not necessarily passing it along right away. If you're just using them so you can use readLine(), pass a second constructor argument of 0, which essentially turns buffering off.

Also see @JonSkeet's answer regarding reading booth stdout and stderr at the same time, in the background.



来源:https://stackoverflow.com/questions/9548232/how-to-get-stdout-and-stderr-in-runtime-exec-in-real-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!