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.
Asked
Active
Viewed 1.5k times
46

Derek Mahar
- 27,608
- 43
- 124
- 174
-
In what way do they not have the desired effect? Also, why do you want to reuse it instead of creating a new one? – zigdon Sep 17 '10 at 18:53
-
2They don't empty the `StringWriter` buffer, which is the effect that I desire. – Derek Mahar Sep 17 '10 at 19:19
-
Did you look the code source of StreamWriter flush ^^ ? /** * Flush the stream. */ public void flush() { } – Thomas Decaux Nov 02 '18 at 16:36
2 Answers
65
How about calling getBuffer().setLength(0)
?

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
2If you initially set the StringWriter to a specified size, will this setLength reduce that size to 0? – E.S. Jun 26 '13 at 00:29
-
2This keeps the capacity of the buffer the same. If you want to deallocate the memory, use `writer.getBuffer().trimToSize();` after setting the length. – thomas88wp Jul 26 '17 at 14:38
2
Alternatively, we could also delete the buffer using the following code:
StringBuffer buf = ****.getBuffer();
buf.delete(0,buf.length());

Bugs
- 4,491
- 9
- 32
- 41

Exception_al
- 1,049
- 1
- 11
- 21
-
Does this clear the buffer contents or deallocate the buffer storage? In this case, I want to clear the contents. – Derek Mahar Jan 16 '17 at 16:38
-
If it deallocates the memory for the cleared Buffer, I am not sure... You could check with buf.capacity() – Exception_al Jan 16 '17 at 16:43
-
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#delete-int-int- is not clear, but seems to suggest that it does not change the buffer size. – Derek Mahar Jan 16 '17 at 16:49