Java introduced try-with-resources feature in Java 7 that helps to close resources automatically after being used.
In other words, we can say that we don’t need to close resources (file, connection etc) explicitly, try-with-resource close that automatically by using the AutoClosable interface.
If you look in Java 7 then you will find that try-with-resources has a limitation that It requires resources to declare locally within its block Like below.
Example Java 7 Resource Declared within resource block
try(FileOutputStream fileStream=new FileOutputStream(“test.txt”);){
}
This code will be executed fine in Java 7 and even with Java 9 because Java maintains its legacy or backward compatibility.
But the below program would not work with Java 7 because we can’t put resource declared outside the try-with-resource.
If we execute this code in Java 7, the compiler generates an error message.
FileOutputStream fileStream=new FileOutputStream(“test.txt”);
try(fileStream){
}
To overcome this error, try-with-resource is enhanced in Java 9 and now we can use reference of the resource that is not declared locally.
test.txt
1 2 |
Let's learn java 9 feature. Learning java is fun.. |
Java9TryWithResourcTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.kkjavatutorials.org; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; /* * Java 9 Try With Resource Enhancement Feature */ public class Java9TryWithResourcTest { public static void main(String[] args) throws IOException { InputStream inputStream = new FileInputStream("test.txt"); Scanner scanner = new Scanner(inputStream); try(inputStream;scanner) { while(scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } } catch (Exception e) { e.printStackTrace(); } } } |
If you run Java9TryWithResourcTest.java as Java Application then it will give the below output:
1 2 |
Let's learn java 9 feature. Learning java is fun.. |
That’s all about Java 9 Try with Resource Enhancement
You May Also Like:
Java 9 Jshell Tutorial
Java 9 private Methods in Interfaces
Java 9 @SafeVarargs Annotation
Java 9 Collection Factory Methods
Java 9 Stream API improvements
If you have any feedback or suggestion please feel free to drop in below comment box.