将控制台输出redirect到java中的string

我有一个返回types为VOID的函数,并直接在控制台上打印。

不过,我需要在string中的输出,以便我可以工作。

因为我不能做任何改变与返回types是VOID函数,所以我不得不redirect输出到string。

我怎样才能在JAVA中redirect它?

有很多关于将stdoutredirect到string的问题,但它们只redirect从用户获取的input,而不是某些函数的输出。

如果函数打印到System.out ,则可以使用System.setOut方法捕获该输出,以更改System.out以转到您提供的PrintStream 。 如果创build连接到ByteArrayOutputStreamPrintStream ,则可以将输出捕获为String

例:

  // Create a stream to hold the output ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); // IMPORTANT: Save the old System.out! PrintStream old = System.out; // Tell Java to use your special stream System.setOut(ps); // Print some output: goes to your special stream System.out.println("Foofoofoo!"); // Put things back System.out.flush(); System.setOut(old); // Show what happened System.out.println("Here: " + baos.toString()); 

这个程序只打印一行:

  Here: Foofoofoo! 

这是一个名为ConsoleOutputCapturer的实用程序类。 它允许输出到现有的控制台,但在场景后面继续捕获输出文本。 您可以控制使用启动/停止方法捕获的内容。 换句话说,调用start开始捕获控制台的输出,一旦你完成捕获,你可以调用stop方法,该方法返回一个String值,该值持有控制台输出,用于启动和停止调用之间的时间窗口。 这个类虽然不是线程安全的。

 import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.List; public class ConsoleOutputCapturer { private ByteArrayOutputStream baos; private PrintStream previous; private boolean capturing; public void start() { if (capturing) { return; } capturing = true; previous = System.out; baos = new ByteArrayOutputStream(); OutputStream outputStreamCombiner = new OutputStreamCombiner(Arrays.asList(previous, baos)); PrintStream custom = new PrintStream(outputStreamCombiner); System.setOut(custom); } public String stop() { if (!capturing) { return ""; } System.setOut(previous); String capturedValue = baos.toString(); baos = null; previous = null; capturing = false; return capturedValue; } private static class OutputStreamCombiner extends OutputStream { private List<OutputStream> outputStreams; public OutputStreamCombiner(List<OutputStream> outputStreams) { this.outputStreams = outputStreams; } public void write(int b) throws IOException { for (OutputStream os : outputStreams) { os.write(b); } } public void flush() throws IOException { for (OutputStream os : outputStreams) { os.flush(); } } public void close() throws IOException { for (OutputStream os : outputStreams) { os.close(); } } } }