一些由Java类库提供的可以通过close方法手动关闭的资源,例如inputStream类型,java.sql.Connection类型的资源。为了避免使用者忘记关闭资源,或者多个资源的使用导致try-finally的嵌套,这种场景使用try-with-resources是更好的选择:
// try-with-resources on multiple resources - short and sweet
static void copy(String src, String dst) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
byte[] buf = new byte[BUFFER_SIZE];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
}
}
// try-with-resources with a catch clause(带catch的使用)
static String firstLineOfFile(String path, String defaultVal) {
try (BufferedReader br = new BufferedReader(
new FileReader(path))) {
return br.readLine();
} catch (IOException e) {
return defaultVal;
}
}
当资源的调用出现异常,资源的关闭也出现异常时try-with-resources能抑制close时的异常,而try-finally会抑制第一个异常,导致错误难以排查。
需要注意的是:使用try-with-resources必须要继承AutoCloseable接口(Java类库与第三方类库中的类中部分资源实现了该接口),按文字理解 流、连接、管道应该都实现了该接口,而ReentrantLock类型的资源由于没有关闭的概念(需要释放),不能使用try-with-resources