I know how to redirect the stdout to a file, but I have no idea on how to redirect it to a string.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Yes - you can use a ByteArrayOutputStream
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
Then you can get the string with 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)
If you want to revert back to the original stream, use:
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));