0

I am implementing a mailx command through Runtime.exec and came across this article which explains the right way of doing it.

JavaWorld : Runtime.exec

I have been through the examples and see that they have introduced a new class StreamGobbler which accepts the InputStream and prints the output. However I fail to understand the reason why this has been introduced. Can anybody please explain.

Also as part of my code , I have written the following

OutputStreamWriter osw = new OutputStreamWriter(proc.getOutputStream())
osw.write(mailBody)
osw.close

Is this implementation correct or there are any pitfalls to it ?

Vivek
  • 2,091
  • 11
  • 46
  • 61
  • Does this answer your question? [Handle Input using StreamGobbler](https://stackoverflow.com/questions/12258243/handle-input-using-streamgobbler) – Dave Jarvis Dec 19 '22 at 06:49

3 Answers3

0

Since your program can potentially succeed (which means the program's output would be available on the Process' getInputStream()) or it can potentially fail (which means the program's error would be available on the Process' getErrorStream(), you should be able to read these in parallel and hence the need for a separate thread which is implemented by the StreamGobbler class. Hope this clarifies to an extent.

Vikdor
  • 23,934
  • 10
  • 61
  • 84
0

Say you don't use the StreamGobbler solution and simply use getInputStream() to obtain the standard output produced by the program. If the execution of the program generates only standard error output, your Java code may hang when you try to read the InputStream returned by getInputStream(). I say "may hang" because I believe the behavior may vary depending on your execution environment. I ran into this issue when executing a JUnit test.

Paulo Merson
  • 13,270
  • 8
  • 79
  • 72
0

ProcessBuilder has a method to redirect the error stream to the input stream (ProcessBuilder.redirectErrorStream) so you do not need a separate thread to read the streams in parallel. However, InputStream.read may block and is not interruptable via Thread.interrupt, so if you need to put a timeout on the read you may want to use a separate thread "StreamGobbler".

Ryan
  • 7,499
  • 9
  • 52
  • 61