If you open many files, and if you don't close them, your operating system will be unable to open any more files after a while.
Also, while your BufferedWriter
has not been garbage collected, the file it was writing to will remain open as far as your operating system is concerned. If that's Windows, you will not be able to delete the file until the file handle is closed, either by the BufferedWriter
finally being garbage collected or by the JVM exiting.
BufferedWriter.close()
flushes the buffer to the underlying stream, so if you forget to flush()
and don't close, your file may not have all the text you wrote to it.
BufferedWriter.close()
also closes the wrapped Writer. When that's a FileWriter, this will ultimately close a FileOutputStream
and tell the OS that you're done writing to the file.
The garbage collector will automatically call close()
, not on the BufferedWriter
or the wrapped FileWriter, but on the FileOuputStream
. So the OS will be happy, but you have to wait for the GC.
However, you always want to release OS resources as soon as you no longer need them. This goes for open files, database connections, print queues ... anything. Trust me on this one.
BufferedWriter.close()
does clear up the internal character buffer, so that memory will be available for garbage collection, even while the BufferedWriter
itself remains in scope.
Check here for more details