Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Writer to String

 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?

like image 808
Pandian Avatar asked Oct 04 '13 12:10

Pandian


People also ask

How do I get the PrintWriter string?

The write(String) method of PrintWriter Class in Java is used to write the specified String on the stream. This String value is taken as a parameter. Parameters: This method accepts a mandatory parameter string which is the String to be written in the Stream. Return Value: This method do not returns any value.

What is StringWriter in Java?

public class StringWriter extends Writer. A character stream that collects its output in a string buffer, which can then be used to construct a string. Closing a StringWriter has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

Does StringWriter need to be closed?

To summarize: it's fine to not close a StringWriter , but the reason to not do the usual right thing, namely try-with-resources, is just because close() declares that it throws an exception that it doesn't actually throw in practice, and handling this precisely is a lot of boilerplate.

How do you clear a StringWriter?

The flush() method of StringWriter Class in Java is used to flush the writer. By flushing the writer, it means to clear the writer of any element that may be or maybe not inside the writer.


2 Answers

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 
like image 176
Grzegorz Żur Avatar answered Oct 17 '22 11:10

Grzegorz Żur


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.

like image 23
Alex Shesterov Avatar answered Oct 17 '22 10:10

Alex Shesterov