Handle Input using StreamGobbler

后端 未结 1 446
遇见更好的自我
遇见更好的自我 2021-01-05 16:14

I have been through the StreamGobbler at the following URL

JavaWorld : Stream Gobbler

I understand the usage and the reason on why it has been implemented.

1条回答
  •  北海茫月
    2021-01-05 16:47

    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.

    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());
    }
    

    0 讨论(0)
提交回复
热议问题