Convert a StreamWriter to an OutputStream in java?

2019-03-25 09:19发布

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?

标签: java io stream
1条回答
劫难
2楼-- · 2019-03-25 09:22

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();
查看更多
登录 后发表回答