9

I am looking for a way to redirect the output of a Process / ProcessBuilder? I know that it works in Java 7 like this:

ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectOutput();
Process process = builder.start();

But I need the same for Java 5/6 ... Any help highly appreciated.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
salocinx
  • 3,715
  • 8
  • 61
  • 110

1 Answers1

4

Sample code for cmd process on Windows 7, working with Java 6:

ProcessBuilder processBuilder = new ProcessBuilder( "cmd" );        
Process process = processBuilder.start();
OutputStream stream = process.getOutputStream();

Javadoc for getOutputStream() method: says "Gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by this Process object."

To redirect the output of a process, I think you can use stream object defined in the code above. You can write it to console etc.

Juvanis
  • 25,802
  • 5
  • 69
  • 87
  • 1
    hey deporter, many thanks for the fast reply. just using process.getInputStream() and putting it into a InputStreamReader works perfect :-) – salocinx Mar 03 '12 at 22:45
  • @NicolasBaumgardt You are welcome. but in the above code i used outputstream, if inputstream is the data that you want, no problem use it. :) – Juvanis Mar 03 '12 at 22:52
  • 4
    hm.. my goal is to read out the stdout of the process I build and the javadoc says: "The stream obtains data piped from the standard output stream of the process represented by this Process object." the javadoc is a bit weird to me in this case... – salocinx Mar 03 '12 at 23:10
  • It's a little confusing: `p.getOutputStream()` returns the stdin of `p` and `p.getInputStream()` returns the stdout of `p`. See [Process](http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html). – ford Nov 02 '13 at 13:08
  • This answer is incomplete as it does not redirect the output as requested. It merely get the stream reference so user can implement it on his/her own. User is expected to start a new thread to do the redirection and continue with the intended work in current thread. – Oliver Gondža Jun 15 '16 at 08:34