Search code examples
javaprocessbuilder

How to redirect the output to a java stream using java.lang.ProcessBuilder


In the ProcessBuilder documentation three methods are provided to redirect the output of a process.

  • ProcessBuilder.Redirect redirectOutput()
  • ProcessBuilder redirectOutput(File file)
  • ProcessBuilder redirectOutput(ProcessBuilder.Redirect destination)

Question : I want to redirect the process output into a stream instead of a File, how this can be achieved.?

Here is the documentation : https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html


Solution

  • How to do :

    When you will start you process you will be able to get a OutputStream via the Process object.

    In the documentation of ProcessBuilder you can find the method Process start().

    With the Process object you will be albe to get the OutputStream via the method abstract OutputStream getOutputStream().

    Documentation :

    Exemple :

    ProcessBuilder processBuilder = ProcessBuilder("/here/your/command1", "/here/your/command2");
    Process process = processBuilder.start();
    OutputStream outputSteeam = process.getOutputStream();