Public Class Closeresource (Public Static Void Main (String Args) (Try (
Public Class Closeresource (Public Static Void Main (String Args) (Try (
the try statement completes normally or abruptly. The following example uses a finally block instead
of a try-with-resources statement:
public class CloseResource{
public static void main(String[] args) {
BufferedReader br=null;
try {
br = new BufferedReader(new FileReader("D:/f1.txt"));
System.out.println(br.readLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();}}}}
The class BufferedReader, in Java SE 7 and later, implements the interface
java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-
resource statement, it will be closed regardless of whether the try statement completes
normally or abruptly (as a result of the method BufferedReader.readLine throwing an
IOException).
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;