Another great thing introduced with Java 7 is the “try-with-resources” construct – previously known as Automatic Resource Management (ARM). This feature is part of Project Coin, which is an umbrella project for a set of small changes to the Java language. You can see my other post on Java 7: Project Coin for more info.
When you work with files, networks streams or databases you follow a common pattern.
- Open resources
- Perform operation
- Close resources
You have to wrap the code in a try-finally block to make sure the resources are closed even if an exception occurs. Take a look at this example that copies the contents of one file to another file.
Java 7 introduces a new construct called try-with-resources. You can initialize the resources inside parenthesis between the try keyword and the opening bracket, and Java will automatically close them for you. This works for all resources that implement the AutoCloseable interface.
Java 7 also contains NIO.2 which improves file operations in Java, and adds several essential features that Java has been missing. For example, now you can copy a file in one line. As a bonus this method not only copies the file contents but also the file metadata!