本文介绍了在Java中将StreamWriter转换为OutputStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用System.setOut将System.out重定向到一个String,它接受一个PrintStream。有没有办法将StringWriter转换为Stream,以便我可以将它传递给setOut?
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?
推荐答案
你做不到确切地说,因为 StringWriter
是 Writer
,而不是 Stream
。但是你可以这样做:
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();
这篇关于在Java中将StreamWriter转换为OutputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!