Java 7 新的 try-with-resources 语句,自动资源释放

从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。

新的语句支持包括流以及任何可关闭的资源,例如,一般我们会编写如下代码来释放资源:

01private static void customBufferStreamCopy(File source, File target) {
02    InputStream fis = null;
03    OutputStream fos = null;
04    try {
05        fis = new FileInputStream(source);
06        fos = new FileOutputStream(target);
07  
08        byte[] buf = new byte[8192];
09  
10        int i;
11        while ((i = fis.read(buf)) != -1) {
12            fos.write(buf, 0, i);
13        }
14    }
15    catch (Exception e) {
16        e.printStackTrace();
17    } finally {
18        close(fis);
19        close(fos);
20    }
21}
22  
23private static void close(Closeable closable) {
24    if (closable != null) {
25        try {
26            closable.close();
27        } catch (IOException e) {
28            e.printStackTrace();
29        }
30    }
31}

代码挺复杂的,异常的管理很麻烦。

而使用 try-with-resources 语句来简化代码如下:

01private static void customBufferStreamCopy(File source, File target) {
02    try (InputStream fis = new FileInputStream(source);
03        OutputStream fos = new FileOutputStream(target)){
04  
05        byte[] buf = new byte[8192];
06  
07        int i;
08        while ((i = fis.read(buf)) != -1) {
09            fos.write(buf, 0, i);
10        }
11    }
12    catch (Exception e) {
13        e.printStackTrace();
14    }
15}

try里面的资源会再try-catch执行完成以后自动关闭。

代码清晰很多吧?在这个例子中,数据流会在 try 执行完毕后自动被关闭,前提是,这些可关闭的资源必须实现 java.lang.AutoCloseable 接口。

转载于:https://www.cnblogs.com/yurujun/p/3480585.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值