Java 通过 StringBuilder 输出流
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18524386/
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
Output stream over a StringBuilder
提问by rocketboy
I think this has been answered but I can't seem to find it.
我认为这已经得到了回答,但我似乎无法找到它。
I have an instance method which writes some contents to an output stream
我有一个实例方法将一些内容写入输出流
writeTo(OutputStream){
//class specific logic
}
I want it to get these contents into a StringBuilder. I can do this via a temporary file but that does not seem right. I want to do something like:
我希望它将这些内容放入 StringBuilder。我可以通过一个临时文件来做到这一点,但这似乎不对。我想做类似的事情:
Stringbuilder sb = /* */;
OutputStream os = outForStringBuilder(sb);//not sure how to do this
instance.writeTo(os); //This should write the contents to Stringbuilder
采纳答案by Centijo
So you are wanting output written to the stream to go to a StringBuffer instead. I am assuming you are doing this because an OutputStream is required somewhere else. You could use ByteArrayOutputStream, but if you want to preserve the StringBuffer behavior, you might simply wrap a StringBuffer in a subclass of OutputStream like the code here:
因此,您希望写入流的输出改为转到 StringBuffer。我假设您这样做是因为其他地方需要一个 OutputStream。您可以使用 ByteArrayOutputStream,但如果您想保留 StringBuffer 行为,您可以简单地将 StringBuffer 包装在 OutputStream 的子类中,如以下代码:
回答by Tom
Use a ByteArrayOutputStreamand then call toString(charSet) - no need for a StringBuilder.
使用ByteArrayOutputStream然后调用 toString(charSet) - 不需要 StringBuilder。