Java7之try-with-resources语句自动关闭资源

1. 使用finally关闭资源

在Java 7之前,如果要关闭一个资源的话,可以使用finally语句,不管try语句里面的代码是否正常执行完毕或出现异常,例如:

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语句里面的代码后,在finally语句里面关闭资源BufferedReader。

2. 使用try-with-resources自动关闭资源

Java 7新增了try-with-resources的语法,支持自动关闭资源,不需要写额外的代码。例如:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

在上述例子中,直接在try后面的小括号里面创建需要被自动关闭的资源,这里是BufferedReader,那么不管try语句里面的代码是否正常执行完毕或出现异常,BufferedReader都会自动被关闭。原理就是资源的close方法会被自动调用,这里是BufferedReader.close(),所以需要被关闭的资源必须要实现接口java.lang.AutoCloseable或java.io.Closeable。

3. 使用try-with-resources自动关闭多个资源

如果想自动关闭多个资源的话,只需要把资源都放到try后面的小括号里面,例如:

public static void writeToFileZipFileContents(String zipFileName,
                                           String outputFileName)
                                           throws java.io.IOException {

    java.nio.charset.Charset charset =
         java.nio.charset.StandardCharsets.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语句里面依次创建了2个资源ZipFile和BufferedWriter,当执行完try语句里面的代码后,ZipFile和BufferedWriter都会被自动关闭,关闭的顺序是与创建的顺序相反。

4. try-with-resources自动关闭资源和catch/finally的执行顺序

try-with-resources与try一样,可以与catch和finally一起使用,catch/finally会在try-with-resources自动关闭资源之后执行。

5. 异常压制

如果try-with-resources语句里面和try语句里面的代码都抛出异常,那么try-with-resources语句抛出的异常会被压制,但可以通过在try语句抛出的异常里面调用Throwable.getSuppressed方法获取。

根据上述例子,可以看出try-with-resources语句简化了关闭资源的代码。

参考链接:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值