java 使用 StreamGobbler 处理输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12258243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handle Input using StreamGobbler
提问by Vivek
I have been through the StreamGobbler at the following URL
我已经通过以下 URL 的 StreamGobbler
I understand the usage and the reason on why it has been implemented. However the scenarios covered are only those wherein there could be an output from the command / handling error's.
我了解使用情况以及实施的原因。然而,涵盖的场景只是那些可能有命令/处理错误输出的场景。
I do not find any scenario wherein StreamGobbler is used to handle inputs. For example, in mailx
, I have to specify the body of the email, which I have done in the following format
我没有找到任何使用 StreamGobbler 处理输入的场景。例如,在 中mailx
,我必须指定电子邮件的正文,我已按以下格式完成
Process proc = Runtime.getRuntime().exec(cmd);
OutputStreamWriter osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(mailBody);
osw.close();
How can this be handled through StreamGobbler , or it is not required to be handled through it.
这如何通过 StreamGobbler 处理,或者不需要通过它处理。
回答by Vikdor
Ideally, you would employ the StreamGobbler
on your error stream (in a separate thread) if you are already expecting something on InputStream
, to look into when the process.waitFor()
returns a non-zero value to find out the error message. If you are not interested in the InputStream
, then you can read the ErrorStream directly in your code, once you are done with giving your inputs to the command.
理想情况下,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());
}