BufferedWriter not writing everything to its output file

前端 未结 9 1827
悲哀的现实
悲哀的现实 2020-11-22 03:35

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

9条回答
  •  情歌与酒
    2020-11-22 04:17

    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.
    • 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.

    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.

提交回复
热议问题