How to convert Writer to String

2020-05-31 09:23发布

问题:

 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?

回答1:

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


回答2:

Several answers suggest using StringWriter. It's important to realize that StringWriter uses StringBuffer internally, meaning that it's thread-safe and has a significant synchronization overhead.

  • 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 using StringBuilderWriter from the commons-io library.

StringBuilderWriter is almost the same as StringWriter, but uses StringBuilder instead of StringBuffer.

Sample usage:

Writer writer = new StringBuilderWriter();
String data = writer.toString();

Note — Log4j has its own StringBuilderWriter implementation which is almost identical to the commons-io version.



回答3:

If you want a Writer implementation that results in a String, use a StringWriter.