Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing stdout when calling Runtime.exec

When experiencing networking problems on client machines, I'd like to be able to run a few command lines and email the results of them to myself.

I've found Runtime.exec will allow me to execute arbitrary commands, but Collecting the results in a String is more interesting.

I realize I could redirect output to a file, and then read from the file, but my spidey sense is telling me there's a more elegant way of doing it.

Suggestions?

like image 877
Allain Lalonde Avatar asked May 19 '09 13:05

Allain Lalonde


2 Answers

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!

like image 122
Brian Agnew Avatar answered Sep 19 '22 15:09

Brian Agnew


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.

like image 33
basszero Avatar answered Sep 23 '22 15:09

basszero