java 在java中将StreamWriter转换为OutputStream?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/565508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:53:09  来源:igfitidea点击:

Convert a StreamWriter to an OutputStream in java?

javaiostream

提问by Yuval Adam

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?

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

回答by Yuval Adam

You can't do that exactly, since StringWriteris a Writer, not a Stream. But you can do this:

你不能完全那样做,因为StringWriter是 a Writer,而不是 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();