如果功能正在打印到
System.out,则可以使用
System.setOut更改
System.out为
PrintStream你提供的方法来捕获该输出。如果创建
PrintStream与的连接
ByteArrayOutputStream,则可以将输出捕获为String。
例:
// Create a stream to hold the outputByteArrayOutputStream baos = new ByteArrayOutputStream();PrintStream ps = new PrintStream(baos);// importANT: Save the old System.out!PrintStream old = System.out;// Tell Java to use your special streamSystem.setOut(ps);// Print some output: goes to your special streamSystem.out.println("Foofoofoo!");// Put things backSystem.out.flush();System.setOut(old);// Show what happenedSystem.out.println("Here: " + baos.toString());该程序仅打印一行:
Here: Foofoofoo!



