Here's a simple code.
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("c:\\hello.txt"))));)
{
writer.write("Hello");
writer.flush();
}
So basically FileOutputStream, OutputStreamWriter, and BufferedWriter are all closeable resources. However they are not explicitly declared as individual variables in the try-with statement. In this case, will Java automatically close all of them after execution or just BufferedWriter object?
The Java will close
BufferedWriter, which means that it will close every stream it wraps. You could've written your code differently, like so:This will not change the way the try-with-resources statement works, but it might be easier to read and understand how closing works.
Here is another way of writing the above code that might help illustrate stream closing (this example is for illustration purposes only).
In Java, if any class is closed, then they will also close the underlying streams. In the above example,
BufferedWriterclass is wrapped aroundOutputStreamWriterwhich wraps aroundFileOutputStreamclass. As you can see, the instancefosis never closed explicitly, but it has been closed because theBufferedWriterhas been closed by the try-with-resources statement.From java doc:
The
try-with-resources statement is atrystatement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. Thetry-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implementsjava.lang.AutoCloseable, which includes all objects which implementjava.io.Closeable, can be used as a resource.The following example reads the first line from a file. It uses an instance of
FileReaderandBufferedReaderto read data from the file.FileReaderandBufferedReaderare resources that must be closed after the program is finished with it:In this example, the resources declared in the
try-with-resources statement are aFileReaderand aBufferedReader. The declaration statements of these resources appear within parentheses immediately after thetrykeyword. The classesFileReaderandBufferedReader, in Java SE 7 and later, implement the interfacejava.lang.AutoCloseable. Because theFileReaderandBufferedReaderinstances are declared in atry-with-resource statement, they will be closed regardless of whether thetrystatement completes normally or abruptly (as a result of the methodBufferedReader.readLinethrowing anIOException).