java7新特新(一) Try-with-resources (TWR)

Try-with-resources (TWR) 

在处理IO的代码中,我们会使用大量的try...catch()...finally...语法,其中会在finally进行IOclose操作,写过python的都知道,这种操作可以使用try-with-resources操作,幸运的是Java7也有了此特性,比如之前的语法:

private void test(URL url, File file) {

    InputStream is = null;

    try {

        is = url.openStream();

        OutputStream out = new FileOutputStream(file);

        try {

            byte[] buf = new byte[4096];

            int len;

            while ((len = is.read(buf)) >= 0)

                out.write(buf, 0, len);

        } catch (IOException iox) {

        } finally {

            try {

                out.close();

            } catch (IOException closeOutx) {

            }

        }

    } catch (FileNotFoundException fnfx) {

    } catch (IOException openx) {

    } finally {

        try {

            if (is != null)

                is.close();

        } catch (IOException closeInx) {

        }

    }

}

而使用try-with-resources语法,则可以简化为:

try (OutputStream out = new FileOutputStream(file); InputStream is = url.openStream()) {

    byte[] buf = new byte[4096];

    int len;

    while ((len = is.read(buf)) > 0) {

        out.write(buf, 0, len);

    }

}

但是使用try-with-resources的时候还是由可能造成资源没有关闭,比如在try()中有错误时,比如:

try ( ObjectInputStream in = new ObjectInputStream(new 

      FileInputStream("someFile.bin")) ) {

 ...

}

比如文件存在,但却不是写入的对象序列,因此会造成不正常打开,此时ObjectInputStream不能正确初始化,且不会关闭,因此正确的方式是分开资源变量:

try ( FileInputStream fin = new FileInputStream("someFile.bin");

         ObjectInputStream in = new ObjectInputStream(fin) ) {

 ...

}

TWR特性是使用了java7的新的接口AutoCloseable,可以使用try-with-resources语法的资源必须实现该接口。而Closeable继承了AutoCloseable,因此我们常用的资源类都可以使用。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值