flush() java file handling

Sumithra picture Sumithra · Oct 28, 2010 · Viewed 13.5k times · Source

What is the exact use of flush()? What is the difference between stream and buffer? Why do we need buffer?

Answer

socket puppet picture socket puppet · Oct 28, 2010

The advantage of buffering is efficiency. It is generally faster to write a block of 4096 bytes one time to a file than to write, say, one byte 4096 times.

The disadvantage of buffering is that you miss out on the feedback. Output to a handle can remain in memory until enough bytes are written to make it worthwhile to write to the file handle. One part of your program may write some data to a file, but a different part of the program or a different program can't access that data until the first part of your program copies the data from memory to disk. Depending on how quickly data is being written to that file, this can take an arbitrarily long time.

When you call flush(), you are asking the OS to immediately write out whatever data is in the buffer to the file handle, even if the buffer is not full.