您可能需要从进程中读取输出流。您可以像这样获得 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 );
}
}
}
}