Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What sense does it make to flush a StringWriter in Java?

Tags:

java

StringWriter has a flush function. What does it mean to flush a string buffer?

like image 907
ceving Avatar asked Sep 20 '12 08:09

ceving


People also ask

What does StringWriter flush do?

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.

What does flush in Java do?

The flush() method of PrintWriter Class in Java is used to flush the stream. By flushing the stream, it means to clear the stream of any element that may be or maybe not inside the stream. It neither accepts any parameter nor returns any value.

What is StringWriter in Java?

StringWriter class is 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 flush a writer in Java?

flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it.


2 Answers

It must have an implementation of flush() because in its superclass Writer that's an abstract method, and StringWriter is not an abstract class. However, if you look at the source code of StringWriter.flush(), which you can find in the file src.zip in your JDK installation directory, you'll see:

/**
 * Flush the stream.
 */
public void flush() {
}

In other words, it does nothing. (There are ofcourse other subclasses of Writer where flush() does do something useful).

The person who implemented this method could have documented that it doesn't do anything, but they didn't.

like image 166
Jesper Avatar answered Sep 28 '22 13:09

Jesper


In general a flush forces a buffer to write its content to the destination, for example writing the bytes to the file on the harddisk.

like image 34
Stefan Avatar answered Sep 28 '22 13:09

Stefan