【问题标题】:Handle Input using StreamGobbler使用 StreamGobbler 处理输入
【发布时间】:2012-09-04 06:56:49
【问题描述】:

我已经通过以下 URL 的 StreamGobbler

JavaWorld : Stream Gobbler

我了解它的用法和实施的原因。然而,所涵盖的场景只是那些可能有来自命令/处理错误的输出的场景。

我没有发现任何使用 StreamGobbler 处理输入的场景。例如,在mailx 中,我必须指定电子邮件的正文,我已经按照以下格式完成了

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

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

【问题讨论】:

    标签: java runtime.exec outputstream


    【解决方案1】:

    理想情况下,如果您已经期待InputStream 上的某些内容,您可以在错误流中使用StreamGobbler(在单独的线程中),以查看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());
    }
    

    【讨论】:

    • 所以在这种情况下,我对 mailx 命令的 InputStream 不感兴趣。但作为故障保险,我应该包括它吗?另外关于我上面提到的邮件正文,这不是 StreamGobbler 的一部分吗?
    • 不是作为故障保护,而是为了通知错误(如果有),您应该始终阅读错误流。如您所说,如果您不希望命令有任何输出,则 inputstream 是可选的。不,邮件正文是您对该流程的输入。
    • 我还是一头雾水。我的命令看起来像这样mailx -s mymail mailsubject mailtoaddress,所以当我执行它并且不会期望输入流中有任何内容时。所以邮件正文与 StreamGobbler 无关,确实需要传递给它。我的理解是否正确,如果我错了,请纠正我
    • 对,您需要传递给 StreamGobbler 的只是 proc.getOutputStream()。请查看我将如何使用它的编辑。
    • 不,不需要。实际上不应该,因为 StreamGobbler 是用于输入流(输入/错误)的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多