Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Input using StreamGobbler

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. 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

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.

like image 526
Vivek Avatar asked Sep 04 '12 06:09

Vivek


1 Answers

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());
}
like image 163
Vikdor Avatar answered Oct 12 '22 23:10

Vikdor