在Java 7之前,我们可以使用finally
关闭资源:
try{
//open resources
}catch(Exception){
//handle exception
}finally{
//close resources
}
在Java 7中,引入了一种新的try-with-resources
方法,它有助于自动关闭资源。
try(open resources, one or more resources){
//...
}
//after try block, the resource will be closed automatically.
1. BufferedReader
1.1在Java 7之前,我们必须手动关闭BufferedReader
。
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在Java 7中,使用try-with-resources
,在try块之后, BufferedReader
将自动关闭。
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
在try-with-resources语句中自动关闭2个资源的Java示例。
2.1在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) {
//...
}
}
参考文献
翻译自: https://mkyong.com/java/try-with-resources-example-in-jdk-7/