1// Create a stream to hold the output
2ByteArrayOutputStream baos = new ByteArrayOutputStream();
3PrintStream ps = new PrintStream(baos);
4// IMPORTANT: Save the old System.out!
5PrintStream old = System.out;
6// Tell Java to use your special stream
7System.setOut(ps);
8// Print some output: goes to your special stream
9System.out.println("Foofoofoo!");
10// Put things back
11System.out.flush();
12System.setOut(old);
13// Show what happened
14System.out.println("Here: " + baos.toString());
15