Capturing stdout when calling Runtime.exec Capturing stdout when calling Runtime.exec java java

Capturing stdout when calling Runtime.exec


You need to capture both the std out and std err in the process. You can then write std out to a file/mail or similar.

See this article for more info, and in particular note the StreamGobbler mechanism that captures stdout/err in separate threads. This is essential to prevent blocking and is the source of numerous errors if you don't do it properly!


Use ProcessBuilder. After calling start() you'll get a Process object from which you can get the stderr and stdout streams.

UPDATE: ProcessBuilder gives you more control; You don't have to use it but I find it easier in the long run. Especially the ability to redirect stderr to stdout which means you only have to suck down one stream.


For processes that don't generate much output, I think this simple solution that utilizes Apache IOUtils is sufficient:

Process p = Runtime.getRuntime().exec("script");p.waitFor();String output = IOUtils.toString(p.getInputStream());String errorOutput = IOUtils.toString(p.getErrorStream());

Caveat: However, if your process generates a lot of output, this approach may cause problems, as mentioned in the Process class JavaDoc:

The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream(), getInputStream(), getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.