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.
TryWithResource1.java
package com.favtuts.classic; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class TryWithResource { public static void main(String[] args) { // Example 1: close the BufferedReader manually 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.favtuts.classic; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class TryWithResource { public static void main(String[] args) { // Example 2: try-with-resources block 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) { //... } }
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-basic/classic