Java 7 try-with-resources example

Before Java 7, we can close a resource with finally :


	try{
		//open resources
	}catch(Exception){
		//handle exception
	}finally{
		//close resources
	}

In Java 7, a new try-with-resources approach is introduced, it helps to close resources automatically.


	try(open resources, one or more resources){
		//...
	}
	//after try block, the resource will be closed automatically.

1. BufferedReader

1.1 Before Java 7, we have to close the BufferedReader manually.


package com.mkyong.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TestApp {

    public static void main(String[] args) {

        BufferedReader br = null;
        String line;

        try {

            br = new BufferedReader(new FileReader("C:\\testing.txt"));
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }

}

1.2 In Java 7, with try-with-resources, the BufferedReader will be closed automatically after try block.


package com.mkyong.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TestApp {

    public static void main(String[] args) {

        String line;

        try (BufferedReader br = new BufferedReader(
                new FileReader("C:\\testing.txt"))) {

            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

		// br will be closed automatically
    }

}

2. JDBC

Java example to auto close 2 resources in a try-with-resources statement.

2.1 Before Java 7


	@Override
    public void update(int postId, String metaValue) {

        Connection connection = null;
        PreparedStatement ps = null;
		
        try {
            connection = dataSource.getConnection();
            ps = connection.prepareStatement(SQL_UPDATE_POST_META);

            ps.setString(1, metaValue);
            ps.setInt(2, postId);
            ps.setString(3, GlobalUtils.META_KEY);

            ps.executeUpdate();

        } catch (Exception e) {
            //
        } finally {

            if (ps != null) {
                ps.close();
            }

            if (connection != null) {
                connection.close();
            }
        }

    }

2.2 Java 7 try-with-resources


	@Override
    public void update(int postId, String metaValue) {

        try (Connection connection = dataSource.getConnection();
             PreparedStatement ps = connection.prepareStatement(SQL_UPDATE_POST_META)) {
            ps.setString(1, metaValue);
            ps.setInt(2, postId);
            ps.setString(3, GlobalUtils.META_KEY);

            ps.executeUpdate()

        } catch (Exception e) {
            //...
        }
		
    }

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
newest oldest most voted
Vijay Raj
Guest
Vijay Raj

What if we have multiple resources to close.

UmeshAwasthi
Guest
UmeshAwasthi

you can open multiple resource in try statement

try (BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
Scanner scanner = new Scanner(new File(fileName1))) {}

infoj
Guest
infoj

Sorry to say but this post is not as detailed as it should be. Please have a look at this post for more detailed explanation.

try-with-resources

trackback
Year Of Security for Java – Week 29 – Manage Resources : John Melton's Weblog
Pankaj
Guest
Pankaj

Hi,

I always liked your article but I think you missed to explain the difference incase of exception handling here. I have written a blog post explaining it in detail. Please have a look.

http://www.journaldev.com/592/try-with-resource-example-java-7-feature-for-automatic-resource-management

najeh
Guest
najeh

exemple de mode non connect? en vb avec sql server svp

cody banks
Guest
cody banks

Thats a good comparison between the two approaches. If you are interested to see how the generated byte-code looks like you can check out – https://blog.srcclr.com/exception-handling-with-try-with-resources-statement-in-java-7/

infoj
Guest
infoj

try-with-resources and multi catch statement in Java 7 help to reduce boiler plate code in Java exception handling.

Andrii Polunin
Guest
Andrii Polunin

Good and succinct comparison between two approaches. However resources should not be chained in try-with-resources statement like this new BufferedReader(new FileReader(“C:\testing.txt”)). Generally it might lead to a situation when inner resource will not be closed. Take a look here for more details: http://www.softwaregeek.net/2014/01/java-7-try-with-resources-statement.html

Rodrigo Feio Dias
Guest
Rodrigo Feio Dias

try-with-resources provides clean code experience

trackback
How to write an Object to file in Java

[…] try-with-resources example in JDK 7 […]