2

I'd like to pipe an OutputStream to more than one receiving OutputStream. Is there out-of-the-box support this, or a simpler way to implement this than my solution?

For arguments sake, say I want to pipe the output of running ls /tmp to System.out AND a ByteArrayOutputStream:

My current solution:

I created a MultiOutputStream class, to delegate to multiple OutputStream's. Is there a simpler/preferred way of achieving the same outcome?

class MultiOutputStream extends OutputStream {

    List<OutputStream> streams

    MultiOutputStream(List<OutputStream> streams = []) {
        this.streams = streams
    }

    @Override
    void write(int b) throws IOException {
        streams.each { it.write(b) }
    }

}

Usage in example:

def baos = new ByteArrayOutputStream()
def proc = 'ls /tmp'.execute()
proc.waitForProcessOutput(
        new MultiOutputStream([System.out, baos]),
        System.err
)
proc.waitForOrKill(5000)
println "Do something with this -> " + new String(baos.toByteArray())
1
  • Hmm, override some log4j stuff Commented Jun 2, 2015 at 7:11

0

Browse other questions tagged or ask your own question.