今天学习下Java 7中引入的try-with-resources语法糖,一个非常有用的特性,它使得在代码中使用资源(例如文件或数据库连接)变得更加简单、方便和安全。所有被打开的系统资源,比如流、文件或者Socket连接等,都需要被开发者手动关闭,否则随着程序的不断运行,资源泄露将会累积成重大的生产事故。
try(资源变量=创建资源对象){
}catch(){
}
例如 InputStream, OutputStream ,Connection, Statement, ResultSet等接口都实现了资源对象关闭接口AutoCloseable,使用 try-with-resource可以不用写finally块,编译器会帮助生成关闭资源的代码,例如:
public class TryWithResourceNewTest {
public static void main(String[] args) {
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("sanFengIn.txt")));
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("sanFengOut.txt")))) {
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
如果不用这个语法糖,手动在finally块中关闭,则代码显得非常臃肿。
public class TryWithResourceOldTest {
public static void main(String[] args) {
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
try {
bin = new BufferedInputStream(new FileInputStream(new File("sanFengIn.txt")));
bout = new BufferedOutputStream(new FileOutputStream(new File("sanFengOut.txt")));
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (bin != null) {
try {
bin.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (bout != null) {
try {
bout.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
但是 try-with-resources 这几个关键点要记住:
1. try() 里面的类,必须实现了 AutoCloseable 接口
2. 在 try() 代码中声明的资源被隐式声明为 final
3 使用分号分隔,可以声明多个资源
try-with-resources 从反编译后的代码来看,编译器自动帮我们生成了 finally 块,并且在里面调用了资源的 close() 方法,所以例子TryWithResourceOldTest 中的close() 方法会在运行的时候被执行。
参考资料
try-with-resources语法详解
如何使用 try-with-resources 优雅地关闭资源
Java的try-with-resources
try-with-resource