I am trying to redirect System.out into a String using System.setOut, which takes a PrintStream. Is there any way to convert a StringWriter into a Stream so that I can pass it to setOut?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can't do that exactly, since StringWriter
is a Writer
, not a Stream
. But you can do this:
// create a ByteArray stream, which will be wrapped by a PrintStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
System.setOut(ps);
// print whatever you got
String result = baos.toString();