我有以下代碼:如何在Runtime.exec中實時獲取stdout和stderr?
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();
}
的問題是作業運行時它會產生大量的輸出,但InputStream的對輸出和錯誤打印作業完成後才能輸出。
是否有一種方法可以實時獲得輸出,即當作業正在輸出時獲取stderr和stdout?
感謝, JJ