O'Reilly logo

Java, A Beginner’s Guide, 5th Edition by Herbert Schildt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required