How can I reuse a StringWriter by flushing out its internal buffer? flush() doesn't seem to do it and I'd like to avoid recreating the object many times.

John Zukowski

To reuse a StringWriter you need to empty out the internal buffer. The way to do this is to get the buffer with getBuffer() and set its length to zero:

StringWriter sw = ...
// use it
StringBuffer buf = sw.getBuffer();
// reuse it
As far as what the purpose of the flush() method is, its clearer if you think of it with something like a BufferedWriter. If you flush() the BufferedWriter, the internal buffer used by the BufferedWriter is flushed. This doesn't clear out the final destination of what the BufferedWriter is attached to. So, in the case of a StringWriter, if it were to use any internal buffering before writing to the StringBuffer, that is what would be flushed. Since the StringWriter doesn't use any internal buffering, directly writing to the StringBuffer, the flush() method effectively does nothing.