Java Reference
In-Depth Information
Automatically Closing a File
In the preceding section, the example programs have made explicit calls to close( ) to close
a file once it is no longer needed. This is the way files have been closed since Java was
first created. As a result, this approach is widespread in existing code. Furthermore, this
approach is still valid and useful. However, beginning with JDK 7, Java has included a fea-
ture that offers another, more streamlined way to manage resources, such as file streams,
by automating the closing process. It is based on another version of the try statement called
try -with-resources , and is sometimes referred to as automatic resource management . The
principal advantage of try -with-resources is that it prevents situations in which a file (or
other resource) is inadvertently not released after it is no longer needed. As explained, for-
getting to close a file can result in memory leaks and could lead to other problems.
The try -with-resources statement has this general form:
Here, resource-specification is a statement that declares and initializes a resource, such as
a file. It consists of a variable declaration in which the variable is initialized with a refer-
ence to the object being managed. When the try block ends, the resource is automatically
released. In the case of a file, this means that the file is automatically closed. (Thus, there
is no need to call close( ) explicitly.) A try -with-resources statement can also include catch
and finally clauses.
The try -with-resources statement can be used only with those resources that implement
the AutoCloseable interface defined by java.lang . This interface defines the close( ) meth-
od. AutoCloseable is inherited by the Closeable interface defined in java.io . Both inter-
faces are implemented by the stream classes, including FileInputStream and FileOut-
putStream . Thus, try -with-resources can be used when working with streams, including
file streams.
As a first example of automatically closing a file, here is a reworked version of the
ShowFile program that uses it:
Search WWH ::




Custom Search