您的位置:首页 > 编程语言 > Java开发

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.

例子:

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());
      }
    }
  }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: