Java7提供了try-with-resources机制,其类似Python中的with语句,将实现了 java.lang.AutoCloseable 接口的资源定义在 try 后面的小括号中,不管 try 块是正常结束还是异常结束,这个资源都会被自动关闭。 try 小括号里面的部分称为 try-with-resources 块。
使用try-with-resources机制的代码如下所示:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
在Java7之前,只能使用下面的语句关闭资源:
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null)
br.close();
}
}
readFirstLineFromFile 方法中,如果 try 块和 try-with-resources 块都抛出了异常,则抛出 try 块中的异常, try-with-resources 块中的异常被忽略; readFirstLineFromFileWithFinallyBlock 方法中,如果方法 readLine 和 close 都抛出了异常,则抛出 finally 块中的异常, try 块抛出的异常被忽略。
参考资料:https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html