问题
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