Tuesday, February 14, 2012

Can I demultiplex streams?


I want to join stderr ( getErrorStream ) and stdout ( getInputStream ) of a Process into a single Stream to be consumed elsewhere. Is there anything in Java's library that will do that for me?



Note: no external libraries . I'm not interested in the existence of a solution provided by, say, Apache Commons IO. I only want to know if there's something that comes with JDK.

2 comments:

  1. You can use a SequenceInputStream to merge the 2 InputStream.

    ReplyDelete
  2. ProcessBuilder.redirectErrorStream(boolean) does what you want.


    public ProcessBuilder redirectErrorStream(boolean redirectErrorStream)

    Sets this process builder's redirectErrorStream property.

    If this property is true, then any error output generated by subprocesses subsequently started by this object's start() method will be merged with the standard output, so that both can be read using the Process.getInputStream() method. This makes it easier to correlate error messages with the corresponding output. The initial value is false.


    EDIT: @Since Java 5 or later so should be widely available.

    ReplyDelete