Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you "empty" a StringWriter in Java?

Tags:

java

io

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.

like image 558
Derek Mahar Avatar asked Sep 17 '10 18:09

Derek Mahar


People also ask

How do you clear a StringWriter in Java?

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.

Do we need to close StringWriter?

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.

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.

How do you write a StringWriter to a file?

FileWriter fw = new FileWriter("file. txt"); StringWriter sw = new StringWriter(); sw. write("some content..."); fw. write(sw.


2 Answers

How about calling getBuffer().setLength(0)?

like image 62
Jon Skeet Avatar answered Sep 29 '22 20:09

Jon Skeet


Alternatively, we could also delete the buffer using the following code:

StringBuffer buf = ****.getBuffer();
buf.delete(0,buf.length());
like image 31
Exception_al Avatar answered Sep 29 '22 20:09

Exception_al