I have a Java program that reads some text from a file, line by line, and writes new text to an output file. But not all the text I write to my BufferedWriter
a
A resource that must be closed when it is no longer needed.
finally {
out.close();//this would resolve the issue
}
Some things to consider:
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. 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. 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. So, Always close your resources (not just files) when you're done with them.
If you really want a peek under the covers, most of the Java API's source is available. BufferedWriter is here.