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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

hey deporter, many thanks for the fast reply. just using process.getInputStream() and putting it into a InputStreamReader works perfect :-)
@NicolasBaumgardt You are welcome. but in the above code i used outputstream, if inputstream is the data that you want, no problem use it. :)
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...
It's a little confusing: p.getOutputStream() returns the stdin of p and p.getInputStream() returns the stdout of p. See Process.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.