Jdk1.7(及以上) 使用 try-with-resources 替代try-catch-finally
2016-12-30 16:53
447 查看
刚刚在看 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.
例子:
还没见过这样的语法,于是乎到官方找了一下解释 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()); } } }
相关文章推荐
- Effective Java 第三版——9. 使用try-with-resources语句替代try-finally语句
- 使用try-with-resources替代try finally释放资源
- JDK1.7新特性之try-with-resources和catch多种异常
- C#中使用try{}catch{}finally{}对系统性能的影响和处理机制(摘录)
- 嵌套使用 try-catch,或者 try-catch 后面没有必要的 finally操作
- 黑马程序员——throws和throw的区别,try、catch和finally的使用场景
- javascript中 try catch finally 的使用
- return在try-catch-finally语句中的使用
- java中为什么要在try-catch中使用finally
- JAVA中try、catch、finally的使用及finally执行顺序详解
- Java异常处理(try、catch、finally使用)
- java只使用try和finally不使用catch的原因和场景
- try-catch-finally的使用
- C#中使用try{}catch{}finally{}对系统性能的影响和处理机制(摘录)
- try - catch - finally使用总结
- 异常处理try...catch(sql 2005版本以上可以使用)
- return 于try{}catch(Exception e){}finally{}语句结合使用的一点注意事项
- 使用try、catch、finally语句块需要注意
- try、catch、finally的使用分析---与 return 相关
- 使用try-with-resources注意的问题