Java introduced try-with-resource feature in Java 7, try-with-resource can automatically close resources like a Java InputStream or a JDBC Connection when you are done with them.
A resource (file, connection, network etc) has to be both declared and initialized inside the try:
When the execution leaves the try-with-resources block, any resource opened within the try-with-resources block is automatically closed, regardless of whether any exceptions are thrown either from inside the try-with-resources block, or when attempting to close the resources.
try(FileOutputStream fileStream=new FileOutputStream("file.txt");){
}
In Java 7, try-with-resources has a limitation that requires resource to declare locally within its block.
In Java 9, we can use reference of the resource that is not declared locally.
FileOutputStream fileStream=new FileOutputStream("file.txt");
try(fileStream){
}
#okayjava #try-with-resource #try-with-resource-example