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.
This general technique is common in code that predates
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
Here are three key points about the
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