Java: Quick and Easy System.out Redirection

Random Computery Photo

I recently found myself in the exciting position of having to put together some unit tests for a Java command-line utility, whose results of course all went straight to System.out. Handily, Java provides some neat functionality to redirect output streams.

I fiddled around with a few output stream types and hit all sorts of trouble, ranging from pipe streams not being flushed often enough to running out of buffer space to synchronization issues.

Finally, a Stackoverflow question on exactly this problem pointed me to an elegant and easy solution that I could just drop in. My snippet is below:

ByteArrayOutputStream pipeOut = new ByteArrayOutputStream();

// Store the current System.out
PrintStream old_out = System.out;

// Replace redirect output to our stream
System.setOut(new PrintStream(pipeOut));

// Do stuff
// ...
// Done stuff

// Revert back to the old System.out
System.setOut(old_out);

// Write the output to a handy string
String output = new String(pipeOut.toByteArray());

This is mostly for my own benefit (less Googling if I need to do this again). But heck, if anyone else finds it useful, all the better.

You probably wouldn't want to use this to redirect vast tomes of logging, but for handling a few lines of text output, it's perfect. Add another couple of lines and you get System.err into the bargain.