try-with-resources语句

所谓try-with-resources语句就是在try后面加上resources,跟平常见到的try-catch语句有差别。

先看个例子:

File srcFile = new File(srcPath);
File dstFile = new File(dstPath);
try (FileInputStream fis = new FileInputStream(srcFile);
    FileOutputStream fos = new FileOutputStream(dstFile)){
    byte[] bytes = new byte[1024];
    int count = fis.read(bytes);
    if(count != -1) {
        fos.write(bytes);
    }
} catch (Exception e) {
    e.printStackTrace();
}

其中try后面圆括号内的东西即为resources,resources必须为实现java.lang.AutoCloseable或者java.io.Closeable接口的类,使用后可以自动close以释放资源,并且resources可以有多个,用分号间隔开。try-catch语句执行完resources即自动释放掉,不需要自己再去close,我们可以简单验证下。

//定义一个自己的Closeable类
class MyCloseable implements Closeable{

    @Override
    public void close() throws IOException {
        Log.v("test", "---close---");
    }
}

//try-with-resources语句
Log.v("test", "---111---");
try (MyCloseable myCloseable = new MyCloseable()) {
    Log.v("test", "---222---");
} catch (Exception e) {
    e.printStackTrace();
}
Log.v("test", "---333---");

//打印结果
V/test: ---111---
V/test: ---222---
V/test: ---close---
V/test: ---333---

使用这种语句可以避免没有释放资源导致内存泄露之类的问题。

需要注意的是,try-with-resources语句在Android SDK大于等于19才可以使用。

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值