46

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.

Derek Mahar
  • 27,608
  • 43
  • 124
  • 174

2 Answers2

65

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    If 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
  • 2
    This 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