我在以下网址浏览过StreamGobbler
我了解其实施的用法和原因。但是,所涵盖的场景只是那些可能存在来自命令/处理错误的输出的场景。
我没有找到使用StreamGobbler处理输入的任何场景。例如,在mailx
中,我必须指定电子邮件的正文,我已按以下格式指定
Process proc = Runtime.getRuntime().exec(cmd);
OutputStreamWriter osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(mailBody);
osw.close();
如何通过StreamGobbler处理,或者不需要通过它处理。
答案 0 :(得分:7)
理想情况下,如果您已经期望StreamGobbler
上的某些内容,则可以在错误流上使用InputStream
(在单独的帖子中),以查看process.waitFor()
何时返回非-zero值以找出错误消息。如果您对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());
}