Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flush in java.io.FileWriter

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?

like image 489
i2ijeya Avatar asked Nov 16 '09 14:11

i2ijeya


People also ask

What does flush do in FileWriter Java?

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.

What is FileWriter flush?

This method is used to flush the writer, which means that this method will remove all the data present inside the writer. It neither accepts any parameter nor returns any value.

What does flush () do in Java?

flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it.

What is flushing output Java?

The flush() method of BufferedOutputStream class in Java is used to flush the buffered output stream. This method is used to compel the bytes of buffered output to be written out to the main output stream.


2 Answers

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.

like image 190
Carl Smotricz Avatar answered Sep 19 '22 20:09

Carl Smotricz


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.

like image 36
Alexander Pogrebnyak Avatar answered Sep 22 '22 20:09

Alexander Pogrebnyak