Java exec method, how to handle streams correctly

后端 未结 2 1993
说谎
说谎 2021-01-18 10:09

What is the proper way to produce and consume the streams (IO) of external process from Java? As far as I know, java end input streams (process output) should be consumed in

2条回答
  •  独厮守ぢ
    2021-01-18 10:53

    waitFor signals that the process ended, but you cannot be sure the threads which collect strings from its stdout and stderr finished also, so using a latch is a step in the right direction, but not an optimal one. Instead of waiting for the latch, you can wait for the threads directly:

    Thread stdoutThread = new Thread(new StreamConsumer(procOut, output)).start();
    Thread stderrThread = ...
    ...
    int ret = exec.waitFor();
    stdoutThread.join();
    stderrThread.join();
    

    BTW, storing lines in StringBuffers is useless work. Use ArrayList instead, put lines there without any conversion, and finally retrieve them in a loop.

提交回复
热议问题