try-with-resources优先于try-finally
Java 类库中包括了许多必须通过调用close方法来手动关闭的资源。都是一些关于文件流、SQL连接。
虽然其中很多资源都是用finalizer()方法作为最后的后盾,但是效果并没有很理想。
我们平时开发中都会去主动调用close()方法关闭资源,但是一部分人会使用try-finally,一部分人使用try-with-resources。有什么区别呢?
首先try-with-resources是JDK7引入的语法,要想使用这种语法,构造出来的资源必须先实现AutoCloseable接口,重写close()方法
如果只是在操作一个资源,看起来并不会有太大区别,try-finally只是多写几行代码。
如果是多个资源呢?
try-finally:
FileInputStream fis = null;
FileReader fr = null;
try {
fis = new FileInputStream("pom.xml");
fr = new FileReader("pom.xml");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}finally {
// 没有判断这两个资源是否为空
try {
fis.close();
fr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
try-with-resources:
try (FileInputStream fis = new FileInputStream("pom.xml");
FileReader fr = new FileReader("pom.xml")) {
System.out.println(fis);
System.out.println(fr);
} catch (IOException e) {
throw new RuntimeException(e);
}
使用try-with-resources不仅使代码变得简洁易懂,也更加不容易出现close()关闭失败的问题
结论
很明显,如果使用需要通过调用close方法来手动关闭的资源,try-with-resources不仅在代码量上,也在简洁度,代码复杂度上优于try-finally