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?
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.
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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With