0

I read that invoking flush method guarantees that the last of the data you thought you had already written actually gets out to the file.I didn't get the meaning of this statement can any one explain clearly what actually flush method invocation will do?

Deepak
  • 2,094
  • 8
  • 35
  • 48
satheesh
  • 1,443
  • 7
  • 28
  • 41
  • possible duplicate of [flush in java.io.FileWriter](http://stackoverflow.com/questions/1742361/flush-in-java-io-filewriter) – pb2q Sep 29 '12 at 18:14

2 Answers2

2

The writers are usually buffered so it waits for the buffer to be filled before it writes it to the file. Flush tells to write the buffer even though it might not be filled yet. It's usually useful when you finish the writing since the last buffer may not be full but you want to finish the writing.

Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
  • what will happen if the object does not invoke flush method and closed the object ...i observed even then it is writing into the file – satheesh Mar 10 '11 at 09:24
  • If you close the file it may flush the buffer automatically but it always good practice to do it yourself. For example Java Writer close() method flushes the buffer first for you. – Jan Zyka Mar 10 '11 at 09:28
  • can you give me any case where it creates problem for not invoking flush method? ..so that i will get clarity – satheesh Mar 10 '11 at 09:32
  • I would copy paste one related anwer from http://stackoverflow.com/questions/1742361/flush-in-java-io-filewriter. I would highly recommend to call flush before close. Basically it writes remaining bufferized data into file. If you call flush explicitly you may be sure that any IOException coming out of close is really catastrophic and related to releasing system resources. When you flush yourself, you can handle its IOException in the same way as you handle your data write exceptions. – Jan Zyka Mar 10 '11 at 09:40
0

Many streams have internal buffers which they use to store data before it is passed on. This prevents a file stream from having to continually write each individual byte to disk (which can be quite expensive). The flush command forces a stream to clear its internal buffers so that, in this case, everything is forced to disk.

Nick
  • 25,026
  • 7
  • 51
  • 83