在JDK7以前,对文件操作,我们需要时刻注意用完后关闭文件。
InputStream in = null;
try {
in = openInputStream();
OutputStream out = null;
try {
out = openOutputStream();
// do something with in and out
} finally {
if (out != null) {
out.close();
}
}
} finally {
if (in != null) {
in.close();
}
}
可以看到,这段代码真是太复杂了,一不小心就出错了。
可喜的是JDK7有了新的措施来解决这类问题,那就是try-with-resources 语句,如:
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(…) {} ,try里面所有实现接口java.lang.AutoCloseable,包括java.io.Closeable的对象,在{}的语句块执行完毕后都会自动的close。
那JDK7以前的版本怎么办呢,guava给我们提供了方法。我们可以把Closeable 的对象注册到Closer对象上,资源使用完毕后,调用closer的close方法,就可以把所有注册了的资源安全的close掉。这个方法虽然没有try-with-resources好用,但是比起传统的jdk做法,要好很多了。
Closer closer = Closer.create();
try {
InputStream in = closer.register(openInputStream());
OutputStream out = closer.register(openOutputStream());
// do stuff with in and out
} catch (Throwable e) { // must catch Throwable
throw closer.rethrow(e);
} finally {
closer.close();
}