在java中将StreamWriter转换为OutputStream?

2024-05-10

我正在尝试使用 System.setOut 将 System.out 重定向到字符串,它需要一个 PrintStream。有什么方法可以将 StringWriter 转换为 Stream 以便我可以将其传递给 setOut 吗?


你不能完全这样做,因为StringWriter is a Writer, not a Stream。但你可以这样做:

// 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在java中将StreamWriter转换为OutputStream? 的相关文章

随机推荐