How to convert Writer to String

后端 未结 3 1368
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 02:25
 Writer writer = new Writer();
 String data = writer.toString();/* the value is not casting and displaying null...*/

Is there any other way to convert

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 02:59

    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.

提交回复
热议问题