Java 如何将 Writer 转换为 String
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19181206/
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
How to convert Writer to String
提问by Pandian
Writer writer = new Writer();
String data = writer.toString();/* the value is not casting and displaying null...*/
Is there any other way to convert a writer to string?
有没有其他方法可以将作家转换为字符串?
采纳答案by Grzegorz ?ur
I would use a specialized writer if I wanted to make a String out of it.
如果我想用它制作一个字符串,我会使用一个专门的作家。
Writer writer = new StringWriter();
String data = writer.toString(); // now it works fine
回答by CommonsWare
If you want a Writer
implementation that results in a String
, use a StringWriter
.
如果您想要一个Writer
导致a 的实现String
,请使用 aStringWriter
。
回答by Alex Shesterov
Several answers suggest using StringWriter
.
It's important to realize that StringWriter
uses StringBuffer
internally, meaning that it's thread-safeand has a significant synchronization overhead.
几个答案建议使用StringWriter
. 重要的是要意识到在内部StringWriter
使用StringBuffer
,这意味着它是线程安全的并且具有显着的同步开销。
If you need thread-safety for the writer, then
StringWriter
is the way to go.If you don't need a thread safe
Writer
(i.e. the writer is only used as a local variable in a single method) and you care for performance — consider usingStringBuilderWriter
from the commons-io library.
如果您需要作家的线程安全,那么
StringWriter
就是要走的路。如果您不需要线程安全
Writer
(即编写器仅用作单个方法中的局部变量)并且您关心性能 -考虑使用StringBuilderWriter
来自commons-io 库。
StringBuilderWriter
is almost the same as StringWriter
, but uses StringBuilder
instead of StringBuffer
.
StringBuilderWriter
与 几乎相同StringWriter
,但使用StringBuilder
代替StringBuffer
。
Sample usage:
示例用法:
Writer writer = new StringBuilderWriter();
String data = writer.toString();
Note — Log4j has its own StringBuilderWriter implementationwhich is almost identical to the commons-io version.
注意——Log4j 有自己的 StringBuilderWriter 实现,它几乎与 commons-io 版本相同。