1. 使用finally关闭资源
在Java 7之前,如果要关闭一个资源的话,可以使用finally语句,不管try语句里面的代码是否正常执行完毕或出现异常,例如:
static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
以上代码相信大家都很熟悉,在执行完try语句里面的代码后,在finally语句里面关闭资源BufferedReader。
2. 使用try-with-resources自动关闭资源
Java 7新增了try-with-resources的语法,支持自动关闭资源,不需要写额外的代码。例如:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
在上述例子中,直接在try后面的小括号里面创建需要被自动关闭的资源,这里是BufferedReader,那么不管try语句里面的代码是否正常执行完毕或出现异常,BufferedReader都会自动被关闭。原理就是资源的close方法会被自动调用,这里是BufferedReader.close(),所以需要被关闭的资源必须要实现接口java.lang.AutoCloseable或java.io.Closeable。
3. 使用try-with-resources自动关闭多个资源
如果想自动关闭多个资源的话,只需要把资源都放到try后面的小括号里面,例如:
public static void writeToFileZipFileContents(String zipFileName,
String outputFileName)
throws java.io.IOException {
java.nio.charset.Charset charset =
java.nio.charset.StandardCharsets.US_ASCII;
java.nio.file.Path outputFilePath =
java.nio.file.Paths.get(outputFileName);
// Open zip file and create output file with
// try-with-resources statement
try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();) {
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
}
在上述例子中,try-with-resources语句里面依次创建了2个资源ZipFile和BufferedWriter,当执行完try语句里面的代码后,ZipFile和BufferedWriter都会被自动关闭,关闭的顺序是与创建的顺序相反。
4. try-with-resources自动关闭资源和catch/finally的执行顺序
try-with-resources与try一样,可以与catch和finally一起使用,catch/finally会在try-with-resources自动关闭资源之后执行。
5. 异常压制
如果try-with-resources语句里面和try语句里面的代码都抛出异常,那么try-with-resources语句抛出的异常会被压制,但可以通过在try语句抛出的异常里面调用Throwable.getSuppressed方法获取。
根据上述例子,可以看出try-with-resources语句简化了关闭资源的代码。
参考链接:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html