Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is the use of flush for a printwriter object?

I'm looking for a theoretical analysis. I mean, how does the buffer system works and what advantage does using flush provide? Kindly illustrate with an example, if possible.

like image 826
Guptill Avatar asked May 01 '15 17:05

Guptill


People also ask

What is the purpose of using flush function?

The flush() method in Python file handling clears the internal buffer of the file. In Python, files are automatically flushed while closing them. However, a programmer can flush a file before closing it by using the flush() method.

What does flush () do in Java?

The flush() method of Writer 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 do not accepts any parameter.

What are flush () and close () used for?

flush() writes the content of the buffer to the destination and makes the buffer empty for further data to store but it does not closes the stream permanently. That means you can still write some more data to the stream. But close() closes the stream permanently.

Does PrintWriter flush on close?

PrintWriter 's close() method does not call flush() .


1 Answers

When you are writing to a text file, BufferedWriter does not write it to disk immediately. Instead, it keeps the data in a buffer in memory.

This has the advantage that many small writes will go into the buffer, and then the data will be written to disk in one go, ie. with one big write, instead of many small writes, which would be inefficient.

When the buffer is full, BufferedWriter will write the data out on it's own, ie. it will do the same thing as calling flush() when the buffer is full.

So when should you call flush() manually ?

  • When you need data to be on disk now. If you have a program which reads data from the file on disk at the same time it is written, you may want to ensure all of the data which is supposed to be on disk is actually there.

  • If you are writing through a network connection, you may want to call flush() so that the data gets sent through the network immediately.

Usually it is not necessary to call flush(). Just write and call close() when finished, and no need for flush() as close() flushes the buffer for you.

like image 107
JonasCz Avatar answered Sep 22 '22 11:09

JonasCz