What is try-with-resources in Java?
What is try-with-resources in Java?
The try-with-resources feature was introduced in the Java 7 version. This feature helps close the resources declared in the try block automatically after the execution of the block is complete.
Advantages
The main benefit of this feature is that the resource will be closed automatically without explicitly doing it.
Requirements
The resources declared have to implement the AutoCloseable interface.
The catch and finally blocks can still be used in a try-with-resources block, and they will operate in the same manner as they would in a regular try block.
Syntax
The general syntax to use try-with-resources is as follows.
try(resource_1_declaration;resource_2_declaration; ...){ }
How to use try-with-resources
In the syntax above, the resources are declared in the try block. You can declare multiple resources in the try block.
After the execution of the try block, the close() method of the resources will be called, which will handle the closing of the resource.
Every resource declaration is separated by a semi-colon (;) in case of multiple resources declared in the try block.
Code
Example 1
In the code below, we use resource objects such as FileInputStream and BufferedInputStream in the try block to read the file and automatically close it once the try block is finished with execution.
import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.IOException;public class Main{public static void main(String[] args) {try(FileInputStream fileInputStream = new FileInputStream("new_file.txt");BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)) {while(bufferedInputStream.available() > 0 ){System.out.print((char)bufferedInputStream.read());}} catch (IOException e) {e.printStackTrace();}}}
Example 2
In the code below, we define a custom class that implements the AutoCloseable interface. In the try block, we create an object of the class. Once the program is run, the close() method of the custom class gets called.
public class Main{static class CustomReader implements AutoCloseable{@Overridepublic void close() {System.out.println("Closing Custom Reader");}}public static void main(String[] args) {try(CustomReader ignored = new CustomReader()) {System.out.println("In Try Block");} catch (Exception e) {e.printStackTrace();}}}