flush in java.io.FileWriter

i2ijeya picture i2ijeya · Nov 16, 2009 · Viewed 41.2k times · Source

I have a question in my mind that, while writing into the file, before closing is done, should we include flush()??. If so what it will do exactly? dont streams auto flush?? EDIT:

So flush what it actually do?

Answer

Carl Smotricz picture Carl Smotricz · Nov 16, 2009

Writers and streams usually buffer some of your output data in memory and try to write it in bigger blocks at a time. flushing will cause an immediate write to disk from the buffer, so if the program crashes that data won't be lost. Of course there's no guarantee, as the disk may not physically write the data immediately, so it could still be lost. But then it wouldn't be the Java program's fault :)

PrintWriters auto-flush (by default) when you write an end-of-line, and of course streams and buffers flush when you close them. Other than that, there's flushing only when the buffer is full.