Try-with resources in Java (Part 5)
Pre-requisites: Exception Handling , File Reading by Other ways
Try-with Resources
- Try-with resources automatically closes the resources which are defined in it.
- We don't have to explicitly write the code to close those resources as it implements an interface called as AutoCloseable .
- This interface already has an abstract method called void close( ) which closes required resources.
Syntax:-
try (resource defined) {//block of code} catch (exception 1) {//user exception prompt}
Advantages of try-with resources
1. finally block not required to close the resource
Let us compare a program by first using try-catch statements and then using same program with try-with resources.
Using try-catch statement :
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public classMyClass{ public static void main(String[] args) { Filefile= new File("C:\\Users\\Desktop\\example.txt"); BufferedReaderbr= null; intline; try { System.out.println("Entering try block"); FileReaderfr= new FileReader(file);br= new BufferedReader(fr); while ((line=br.read()) != -1) { System.out.print((char)line); } } catch (FileNotFoundException e) { System.out.println("File Not Found:" +file.toString()); } catch (IOException e) { System.out.println("Unable to perform I/O operations on file:"+file.toString()); } finally { System.out.println("Entering finally block"); try {br.close(); System.out.println("Successfully closed BufferedReader:"+br.toString()); } catch (IOException e) { System.out.println("Unable to close BufferedReader:"+br.toString()); } } } }
Output:- ( If file is found )
Entering try block
Hello I am a Text File.
This is my 2nd line.
This is my 3rd line.
Thank You.
Entering finally block
Successfully closed BufferedReader: java.io.BufferedReader@1f6f0bf
Here we had to add an extra try-catch block to close BufferedReader as it is suspicious of throwing IOException.
Now let us see the same program using try-with resources.
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public classMyClass{ public static void main(String[] args) { Filefile= new File("C:\\Users\\Desktop\\example.txt"); intline;//here try-with resource is usedtry (BufferedReaderbr=new BufferedReader(new FileReader(file))) {//resource usedSystem.out.println("Entering try block"); while ((line=br.read()) != -1) { System.out.print((char)line); } } catch (FileNotFoundException e) { System.out.println("File Not Found:" +file.toString()); } catch (IOException e) { System.out.println("Unable to perform I/O operations on file:"+file.toString()); } } }
Output:- ( If file is found )
Entering try block
Hello I am a Text File.
This is my 2nd line.
This is my 3rd line.
Thank You.
While using try-with resources , the work of finally block is done by the resource itself as it implements the Autoclosable( ) interface.
Here I have written bufferedReader in another format. If we separate the lines it would be read as:
Filefile= new File("C:\\Users\\Desktop\\example.txt"); intline; FileReaderfr=new FileReader(file); BufferedReaderbr=new BufferedReader(fr);
2. Can use multiple resources at a time
Syntax:-
try((resource 1); (resource 2); (resource 3)) {// code to be executed}
For example here , Let's see an example of reading a file by using scanner and a BufferedReader so that it forms an example of above mentioned type;
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public classMyClass{ public static void main(String[] args) { Filefile= new File("C:\\Users\\bharg\\Desktop\\example.txt"); intline;//using try multi resourcetry (BufferedReaderbr= new BufferedReader(new FileReader(file)); Scannerscan= new Scanner(file)) { System.out.println("Reading by BufferedReader"); while ((line=br.read()) != -1) { System.out.print((char)line); } System.out.println("Reading by Scanner"); while (scan.hasNext()) { System.out.println(scan.nextLine()); } } catch (FileNotFoundException e) { System.out.println("Unable to find file:" +file.toString()); } catch (IOException e) { System.out.println("Unable to perform I/O operations on file:"+file.toString()); } catch (Exception e) { System.out.println("Some other error occured."); } } }
Output:-
Reading by BufferedReader
Hello I am a Text File.
This is my 2nd line.
This is my 3rd line.
Thank You.
Reading by Scanner
Hello I am a Text File.
This is my 2nd line.
This is my 3rd line.
Thank You.
In Java 7 when try-with resources was introduced , to use the resource the resource must be defined in the block of try. So to improve this , Java 9 approved the definition of resources locally and can be used in the try-with resources block by just mentioning its variable name.
Before Java 9:-
Filefile=new File("C:\\Users\\Desktop\\example.txt"); try (Scannerscan=new Scanner(file)) {//code to be executed}
After Java 9:-
Filefile=new File("C:\\Users\\Desktop\\example.txt"); Scannerscan=new Scanner(file) try (scan) {//code to be executed}

