开发者

Redirect stdout to a string in Java

开发者 https://www.devze.com 2023-01-24 22:27 出处:网络
I know how开发者_如何学JAVA to redirect the stdout to a file, but I have no idea on how to redirect it to a string.Yes - you can use a ByteArrayOutputStream:

I know how开发者_如何学JAVA to redirect the stdout to a file, but I have no idea on how to redirect it to a string.


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)));
0

精彩评论

暂无评论...
验证码 换一张
取 消