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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With