将标准输出重定向到 Java 中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4183408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirect stdout to a string in Java
提问by Fengqian Li
I know how to redirect the stdout to a file, but I have no idea on how to redirect it to a string.
我知道如何将标准输出重定向到一个文件,但我不知道如何将它重定向到一个字符串。
回答by Bozho
Yes - you can use a ByteArrayOutputStream
:
是的 - 您可以使用ByteArrayOutputStream
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
Then you can get the string with baos.toString()
.
然后你可以得到字符串baos.toString()
。
To specify encoding (and not rely on the one defined by the platform), use the PrintStream(stream, autoFlush, encoding)
constructor, and baos.toString(encoding)
要指定编码(而不是依赖于平台定义的编码),请使用PrintStream(stream, autoFlush, encoding)
构造函数,并且baos.toString(encoding)
If you want to revert back to the original stream, use:
如果要恢复到原始流,请使用:
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));