Signup/Sign In
LAST UPDATED: SEPTEMBER 4, 2020

Try-with-resources

Java try-with-resources is a feature that was first added into the Java 7 version. It helps to automatically close resources like a Java InputStream or a JDBC Connection after finishing the task.

Any object or resource that implements java.lang.AutoCloseable Interface can be used as a resource. For example, FileOutputStream class implements AutoCloseable interface so can be used inside the try-with-resources statement.

If we don't use try-with-resources then we need to manually close the connection by using the close() method. In case we forgot to close the connection then it may lead to the resource leakage issue which is vulnerable.

Let's see the use of try-with-resources by using some examples.

Example: older approach

This is a simple example that is used in early versions of Java to safely open the resources in the try block. Notice, we used the close() method to close the fileStream instance.

import java.io.FileOutputStream;
import java.io.IOException;

public class Main { 
	public static void main(String[] args) throws IOException{  
        FileOutputStream fileStream = new FileOutputStream("abc.txt");
        try{  
            String greeting = "Hello from Studytonigh.";      
               byte b[] = greeting.getBytes();       
               fileStream.write(b);      
               System.out.println("File written");           
       }catch(IOException e) {  
           System.out.println(e);  
       }
        finally {
        	// closing stream
        	fileStream.close();
        }
	}
}


File written

Example: Java 7

This is what we can do with Java 7. Here, we passed a fileStream instance to try-with-resource. It is a new syntax of try block which is known as try-with-resource. Notice, we did not close the fileStream instance here because now it will be closed automatically.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class Main {
	public static void main(String[] args) throws FileNotFoundException{  
        try(FileOutputStream fileStream = new FileOutputStream("abc.txt");){  
            String greeting = "Hello from Studytonight.";      
               byte b[] = greeting.getBytes();       
               fileStream.write(b);      
               System.out.println("File written");           
       }catch(Exception e) {  
           System.out.println(e);  
       }         
	}
}


File written

Java 9: Try-with-resources statement Improvement

Example: Java 9

In Java 9, the try-with-resources statement is improved so that we can declare resource(object) outside the try and then pass it into the try statement. See the below example, here we created FileOutputStream object outside the try and later passed its reference to the try-statement.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class Main {
	public static void main(String[] args) throws FileNotFoundException{
        FileOutputStream fileStream = new FileOutputStream("abc.txt");  
        try(fileStream){  
            String greeting = "Hello from Studytonight.";      
               byte b[] = greeting.getBytes();       
               fileStream.write(b);      
               System.out.println("File written");           
       }catch(Exception e) {  
           System.out.println(e);  
       }         
	}
}


File written

Java 9 JDBC Example

The resource can be any valid object that implements the AutoCloseable interface. Here, Connection interface extends the AutoCloseable interface so that we can pass it into the try-with-resources statement.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
	public static void main(String[] args) throws SQLException{
		Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/company","db_user","user_password");
		 try(con) {
	            Statement stmt=con.createStatement();  
	            ResultSet rs=stmt.executeQuery("select * from emp");  
		            while(rs.next()){    
		                System.out.println(rs.getInt(1)+""+rs.getString(2));    
		            }  
		        }  
		        catch(SQLException e){   
		            System.out.println(e.getMessage());  
		        }         
	}
}

Example: Multiple Resources

Java allows us to pass multiple resources. So, if we have multiple resources then try statement will handle all the resources and close after performing the tasks.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Main { 
	public static void main(String[] args) throws FileNotFoundException{ 
		FileInputStream fileStream = new FileInputStream("abc.txt");
		BufferedInputStream bufferedInput = new BufferedInputStream(fileStream);
		try( fileStream; 
				bufferedInput;
				)
		{  
			int data = bufferedInput.read();
			while(data != -1){
				System.out.print((char) data);
				data = bufferedInput.read();
			}        
		}catch(Exception e) {  
			System.out.println(e);  
		}         
	}
}


About the author:
I am a Java developer by profession and Java content creator by passion. I have over 5 years of experience in Java development and content writing. I like writing about Java, related frameworks, Spring, Springboot, etc.