In general, a stream must be closed when it is no longer needed. Failure to do so can lead to memory leaks and resource starvation.
Beginning with
JDK 7 , there are two basic ways in which you can close a stream. The first is to explicitly call close() on the stream. This is the traditional
approach that has been used since the original release of Java . With this approach, close() is typically called within a finally block.try This general technique is common in code that predates JDK 7 . The second approach to closing a stream is to automate the process by using the new try-with-resources
statement that was added by JDK 7 . The try-withresources statement is an enhanced form of try that has the following form:try (resource-specification) Here, resource-specification is a statement or statements that declares and initializes a resource, such as a file or other stream-related resource. It consists of a variable declaration in which the variable is initialized with a reference 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.Here are three key points about the try-with-resources statement:
Also, remember that the scope of the declared resource is limited to the try-with-resources statement. The principal advantage of try-with-resources is that the resource (in this case, a stream) is closed automatically when the try block ends. Thus, it is not possible to forget to close the stream, for example. The try-with-resources approach also typically results in shorter, clearer, easier-to-maintain source code. One last point: The examples that use try-withresources must be compiled by a JDK 7 or later. They won’t work with an older compiler. The examples that use the traditional approach can be compiled by older versions of Java.
|