当前位置 博文首页 > Leo's Blog:Jdk1.7(及以上) 使用 try-with-resources 替代try-
刚刚在看 Jedis's Wiki 的时候,发现里边的代码,用了一句
还没见过这样的语法,于是乎到官方找了一下解释 ?http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
只要你的对象实现了AutoCloseable 或 Closeable,在try代码块结束之前,会自动关闭资源.
我还用 Idea 找了一下 AutoCloseable 的实现类,常用的 Stream,Reader 都实现了.
所以常用的这些Stream和Reader都可以放心使用try-with-resources.
例子:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
?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()); ? ? ? } ? ? } ? }