您可能需要從流程中讀取輸出流。你可以像這樣得到stdout和stderr流:
InputStream stdout = process.getInputStream();
InputStream stderr = process.getErrorStream();
您可以創建工作線程以異步讀取這些流。
Thread threadOut = new Thread(new MyInputStreamSink(stdout, "out"));
Thread threadErr = new Thread(new MyInputStreamSink(stderr, "err"));
threadOut.setDaemon(true);
threadErr.setDaemon(true);
threadOut.setName(String.format("stdout reader"));
threadErr.setName(String.format("stderr reader"));
threadOut.start();
threadErr.start();
下面是一個Runnable的實現,它使用流的輸出。
private static class MyInputStreamSink implements Runnable {
private InputStream m_in;
private String m_streamName;
MyInputStreamSink(InputStream in, String streamName) {
m_in = in;
m_streamName = streamName;
}
@Override
public void run() {
BufferedReader reader = null;
Writer writer = null;
try {
reader = new BufferedReader(new InputStreamReader(m_in));
for (String line = null; ((line = reader.readLine()) != null);) {
// TODO: Do something with the output, maybe.
}
} catch (IOException e) {
s_logger.log(Level.SEVERE, "Unexpected I/O exception reading from process.", e);
}
finally {
try {
if (null != reader) reader.close();
}
catch (java.io.IOException e) {
s_logger.log(Level.SEVERE, "Unexpected I/O exception closing a stream.", e);
}
}
}
}
從[工藝的Javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html):「*未能及時寫輸入流或讀子流程的輸出流可能導致子流程阻塞,甚至導致死鎖。*「。這可能是你的問題嗎? – assylias