How to convert Writer to String

后端 未结 3 1347
隐瞒了意图╮
隐瞒了意图╮ 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.

    0 讨论(0)
  • 2021-02-05 03:14

    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
    
    0 讨论(0)
  • 2021-02-05 03:16

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

    0 讨论(0)
提交回复
热议问题