As of Java 7 we can code a try statement that declares one or more resources. Each resource is an object that must be closed after the program is finished. The try-with-resources statement ensures that each resource is closed at the end of the statement. Each object considered as a resource must be instantiated from a class that implements java.lang.AutoCloseable.
package com.abelski.samples; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class TryResourcesDemo { public static void main(String[] args) { try { String str = readTextFile("bb.txt"); System.out.println(str); } catch(IOException e) { e.printStackTrace(); } } static String readTextFile(String path) throws IOException { StringBuilder builder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(path))) { String str = null; while((str = br.readLine())!=null) { builder.append(str).append("\n"); } } return builder.toString(); } }
The following video clips shoes the execution of this code sample and explains it.