How to convert Writer to String How to convert Writer to String android android

How to convert Writer to String


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


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.


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