• Java 7新特性-TWR(Try-with-resources)


    Try-with-resources (TWR) 

    在处理IO的代码中,我们会使用大量的try...catch()...finally...语法,其中会在finally进行IO的close操作,写过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,因此我们常用的资源类都可以使用

  • 相关阅读:
    西电大第十六届程序设计竞赛 A-GRE
    浙南联合训练赛 B-Laptops
    STL之multimap
    Python编程练习:平方值格式化
    Python编程练习:使用 turtle 库完成玫瑰花的绘制
    Python编程练习:简单的闹钟提醒
    Python编程练习:使用 turtle 库完成叠边形的绘制
    Python编程练习:使用 turtle 库完成正方形的绘制
    Python编程练习:使用 turtle 库完成六边形的绘制
    Spark 介绍
  • 原文地址:https://www.cnblogs.com/cy0628/p/15218327.html
Copyright © 2020-2023  润新知