将控制台输出重定向到java中的字符串 [英] Redirect console output to string in java
问题描述
我有一个函数的返回类型是VOID ,它直接打印在控制台上。
I have one function whose return type is VOID and it prints directly on console.
但是我需要输出的字符串我可以工作。
However I need that output in string so that I can work on it.
由于我不能做任何更改函数与返回类型是VOID所以我必须重定向到字符串的输出。
As I cant make any changes with function with return type is VOID so I have to redirect that output to string.
如何在JAVA中重定向?
How can I redirect it in JAVA?
有很多关于将stdout重定向到字符串的问题,不输出一些函数...
There are many questions regarding redirecting stdout to string but they redirect only input taken from user and not output of some function...
推荐答案
如果函数打印到 System.out
,您可以使用
System.setOut
方法将 System.out
更改为转到您提供的 PrintStream
。如果创建 PrintStream
连接到 ByteArrayOutputStream
,那么您可以将输出捕获为字符串
。
If the function is printing to System.out
, you can capture that output by using the System.setOut
method to change System.out
to go to a PrintStream
provided by you. If you create a PrintStream
connected to a ByteArrayOutputStream
, then you can capture the output as a 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!
这篇关于将控制台输出重定向到java中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!