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?

vivek_jonam
  • 3,237
  • 8
  • 32
  • 44

4 Answers4

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;
        }
    }
}
sambe
  • 256
  • 1
  • 4
  • 6
    [The `out.close();` line is missing](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/io/BufferedWriter.java?av=f#259) in the Java 8 `BufferedWriter` – Mihai Jul 30 '15 at 13:03
  • 13
    @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. – Aqeel Ashiq Jun 16 '16 at 08:05
3

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

harsh
  • 7,502
  • 3
  • 31
  • 32
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

Community
  • 1
  • 1
Abhishek
  • 91
  • 2
  • 12
  • 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) – sambe May 17 '13 at 09:22
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

Community
  • 1
  • 1
Arpit
  • 12,767
  • 3
  • 27
  • 40