Is it necessary to close a FileWriter, provided it is written through a BufferedWriter?

vivek_jonam picture vivek_jonam · May 16, 2013 · Viewed 30.7k times · Source

Consider a BufferedReader as below:

writer = new BufferedWriter(new FileWriter(new File("File.txt"), true));

In this case at the end of the application, I am closing the writer with writer.close()

Will this be enough? Won't that FileWriter created with new FileWriter(new File("File.txt"), true) need to be closed?

Answer

sambe picture sambe · May 16, 2013

It is not necessary to close it, because BufferedWriter takes care of closing the writer it wraps.

To convince you, this is the source code of the close method of BufferedWriter:

public void close() throws IOException {
    synchronized (lock) {
        if (out == null) {
            return;
        }
        try {
            flushBuffer();
        } finally {
            out.close();
            out = null;
            cb = null;
        }
    }
}