使用StreamGobbler处理输入(Handle Input using StreamGobbl

2019-06-27 18:55发布

我已经通过StreamGobbler以下网址

JavaWorld的:流gobbler之

据我所知,使用和为什么它已经实施的原因。 然而所覆盖的情况是只有那些其中有可能是从命令/处理错误的输出。

我不觉得其中StreamGobbler是用来处理输入的任何情况。 例如,在mailx ,我必须指定的电子邮件,我在下面的格式做了身体

Process proc = Runtime.getRuntime().exec(cmd);
OutputStreamWriter osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(mailBody);
osw.close();

这又如何通过StreamGobbler来处理,或者不需要通过它来处理。

Answer 1:

理想情况下,你会聘请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());
}


文章来源: Handle Input using StreamGobbler