Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 927
vivek_jonam Avatar asked May 16 '13 10:05

vivek_jonam


1 Answers

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;
        }
    }
}
like image 90
sambe Avatar answered Oct 13 '22 00:10

sambe