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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access