如果功能正在打印到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!