[ACCEPTED]-flush() java file handling-file-handling

Accepted answer
Score: 15

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

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

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

Score: 5

The data sometimes gets cached before it's 3 actually written to disk (in a buffer) flush 2 causes what's in the buffer to be written 1 to disk.

Score: 3

flush tells an output stream to send all the 11 data to the underlying stream. It's necessary 10 because of internal buffering. The essential 9 purpose of a buffer is to minimize calls 8 to the underlying stream's APIs. If I'm 7 storing a long byte array to a FileOutputStream, I don't 6 want Java to call the operating system file 5 API once per byte. Thus, buffers are used 4 at various stages, both inside and outside 3 Java. Even if you did call fputc once per byte, the 2 OS wouldn't really write to disk each time, because 1 it has its own buffering.

More Related questions