黑马程序员----java7新特性之自动关闭资源

 ——- android培训java培训、期待与您交流! ———-
java.lang.Interface AutoCloseable Since: 1.7

自动关闭资源接口,Closeable的一个父接口,所有实现Closeable的类都可以自动关闭。

使用方法

try (   /*这儿写打开资源的代码,声明变量也必须放在此处,此处创建的对象
        必须实现AutoCloseable接口,否则编译不通过,结尾圆括号后不能
        写代码*/
     ) 
  {
      /*在此处进行资源调用*/
  } catch (IOException e) {
      //处理异常的代码
 }

示例代码
文件拷贝

public static void main(String[] args) {
    try(//将打开资源的代码卸载try后面的小括号中
        InputStream is=new FileInputStream("C:/文件夹/1280.jpg");
        OutputStream os=new FileOutputStream("C:/1280.jpg");
        ){//在小括号后的大括号中使用打开的资源,使用完后,虚拟机会帮助自动关闭前面打开的资源
            byte[] b = new byte[1024];
            while(-1!=is.read(b)){
            os.write(b);}
        }catch (IOException e) {

        }

对比代码
手动关闭资源

InputStream in = null;
OutputStream out = null;
try {
    n = new FileInputStream("SrcFileName");
    out = new FileOutputStream("TarFileName");
    byte[] buff = new byte[1024];
    while ((in.read(buff)) != -1) {
        out.write(buff);// 读多少,同时就往外写多少
    }
} catch (FileNotFoundException e) {
            e.printStackTrace();
} catch (IOException e) {
            e.printStackTrace();
} finally {必须执行的代码,一定要关闭outtry {
        if (out != null) {//关闭之前要判断out不为空,否则会报错
        out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {// finnaly嵌套,无论out是否关闭,都应该关闭in
        try {
            if (in != null) {//关闭之前要判断in流不为空,否则会报错
                in.close();
                }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用自动关闭资源可以免除繁琐的手动关闭资源一级可能带来的异常,省时省力。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值