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, JDK 7 adds a new feature that offers another, more streamlined way to manage resources, such as file streams, by automating the closing process. It is based on a new 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 ...

Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.