Saturday, April 28, 2012

How to capture System.out and System.err


Sometimes you need to capture the text being written to a PrintStream by a 3rd party component. Here it is a simple solution for out and err PrintStreams:

//System.out
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
System.setOut(new PrintStream(pipeOut));
// now read from pipeIn

//System.err
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
System.setErr(new PrintStream(pipeOut));
// now read from pipeIn

No comments:

Post a Comment