How to : Java Capture Output From Console

Well, the topic pretty says everything. So, here’s the solution.

1
2
3
4
5
6
final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
System.setOut(new PrintStream(myOut));

// test stuff here...

final String standardOutput = myOut.toString();

The idea is just redirect the System.out to another PrintStream and you can use information in the PrintStream.

Mar 1st, 2011

Comments