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

4

15

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?

Holocrine answered 16/5, 2013 at 10:17 Comment(0)
E
22

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;
        }
    }
}
Estelaestele answered 16/5, 2013 at 10:24 Comment(3)
The out.close(); line is missing in the Java 8 BufferedWriterGisellegish
@A.Roshenko look closely, the try block has been replaced with try-with block in java 8 BufferedReader. So, same thing, underlying writer is still being closed in java 8 as well.Mccullum
Why do we need to call out.close() explicitly? Why wouldn't the BufferedWriter's destructor flush the buffer automatically?Selfpropelled
A
3

Yes writer.close() closes underlying writers/streams as well.

Alphaalphabet answered 16/5, 2013 at 10:24 Comment(0)
N
3

It is better to close each open stream individually as all are separate stream. If there are some error occurs in nested stream, then stream won't get close. So its better to close each nested stream exclusively.

For more details refer following link:

Correct way to close nested streams and writers in Java

Nodular answered 16/5, 2013 at 10:26 Comment(1)
Thanks for linking in this question. But I disagree that it's any better to close the inner writers as well, because: 1) the finally clause (as you see in my answer) guarantees that the inner writer's close method is called 2) In the (rare) case that out.close() might throw an exception, the writer's member variables out and cb are not set to null, which is no problem because they are plain objects (not system resources, like e.g. a file handle)Estelaestele
I
0

You need to close the outermost streams only. rest of the streams are temporary and will be closed automatically. if you create the streams separately and then nested them, in that case you need to close the individual stream. Check this Question also Correct way to close nested streams and writers in Java

Infra answered 16/5, 2013 at 10:26 Comment(1)
No, you don't 'need to close the individual stream[s]'. You only need to close the outermost stream.Ptosis

© 2022 - 2024 — McMap. All rights reserved.