Viv*_*vek 6 java outputstream runtime.exec
我通过以下URL浏览了StreamGobbler
我理解它的用法和原因.但是,所涵盖的场景只是那些可能存在来自命令/处理错误的输出的场景.
我没有找到使用StreamGobbler来处理输入的任何场景.例如,在mailx,我必须指定电子邮件的正文,我已按以下格式完成
Process proc = Runtime.getRuntime().exec(cmd);
OutputStreamWriter osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(mailBody);
osw.close();
Run Code Online (Sandbox Code Playgroud)
如何通过StreamGobbler处理,或者不需要通过它处理它.
理想情况下,StreamGobbler如果您已经在期待某些内容InputStream,则可以使用错误流(在单独的线程中),查看何时process.waitFor()返回非零值以查找错误消息.如果您对此不感兴趣InputStream,那么一旦完成对命令的输入,您就可以直接在代码中读取ErrorStream.
Process proc = Runtime.getRuntime().exec(cmd)
// Start a stream gobbler to read the error stream.
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream());
errorGobbler.start();
OutputStreamWriter osw = new OutputStreamWriter(proc.getOutputStream())
osw.write(mailBody)
osw.close();
int exitStatus = proc.waitFor();
if (0 != exitStatus) {
/*
* If you had not used a StreamGobbler to read the errorStream, you wouldn't have
* had a chance to know what went wrong with this command execution.
*/
LOG.warn("Error while sending email: " + errorGobbler.getContent());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17304 次 |
| 最近记录: |