What is the correct way to "empty" a StringWriter
in Java so that I can reuse the StringWriter
without having to create a new one? Neither StringWriter.flush()
nor StringWriter.close()
seem to have the desired effect.
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. It neither accepts any parameter nor returns any value. Parameters: This method does not accepts any parameter.
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.
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.
FileWriter fw = new FileWriter("file. txt"); StringWriter sw = new StringWriter(); sw. write("some content..."); fw. write(sw.
How about calling getBuffer().setLength(0)
?
Alternatively, we could also delete the buffer using the following code:
StringBuffer buf = ****.getBuffer();
buf.delete(0,buf.length());
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