Java 7中try-with-resources简介说明
下文笔者讲述java中try-with-resources场景示例,如下所示
必须手动关闭BufferedReader 。
java7之前,释放资源代码
try{
//open resources
}catch(Exception){
//handle exception
}finally{
//close resources
}
java7中,引入全新的释放
在Java7中
引入一种新try-with-resources方法
有助于自动关闭资源
try(open resources, one or more resources){
//...
}
//try之后,将自动释放资源
BufferedReader
在Java 7之前,必须手动关闭BufferedReader 。
package com.java265.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();
}
}
}
}
try-with-resources自动释放资源示例分享
package com.java265.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("d:\\testing.txt"))) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// br will be closed automatically
}
}
try-with-resources自动关闭JDBC的示例
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();
}
}
}
//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) {
//...
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


