简介
try-with-resources语句是一个声明一个或多个资源的try语句。 资源是一个对象,必须在程序完成后关闭它。 try-with-resources语句确保在语句结束时关闭每个资源。 实现java.lang.AutoCloseable的任何对象(包括实现java.io.Closeable的所有对象)都可以用作资源。
以下示例从文件中读取第一行。 它使用BufferedReader实例从文件中读取数据。 BufferedReader是一个在程序完成后必须关闭的资源:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
JDK1.7之前的做法
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-with-resources语句中声明一个或多个资源。 以下示例检索zip文件zipFileName中打包的文件的名称,并创建包含这些文件名称的文本文件:
public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
throws java.io.IOException {
java.nio.charset.Charset charset = java.nio.charset.Charset.forName("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语句可以像普通的try语句一样有catch和finally块。 在try-with-resources语句中,在声明的资源关闭后运行任何catch或finally块。