爱程序网

1.3.4 try-with-resources (TWR)

来源: 阅读:

其基本设想是把资源(比如文件或类似的东西)的作用域限定在代码块内,当程序离开这个代码块时,资源会被自动关闭;

要确保try-with-resources生效,正确的用法是为各个资源声明独立变量;

目前TWR特性依靠一个新定义的接口实现AutoCloseable;TWR的try从句中出现的资源类都必须实现这个接口;(并非所有的资源相关的类都采用了这项新技术;JDBC4.1已经具备了这个特性;)

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

public class CoinTWR {

    @SuppressWarnings("null")
    public static void main(String[] args) throws IOException {// 抛出异常
        
        /** 资源管理 **/
        try (FileInputStream fin = new FileInputStream("someFile.bin");
                ObjectInputStream in = new ObjectInputStream(fin)) {
            // ...
        }
        
        /** 改善了错误跟踪的能力(注意其中被抑制的NullPointerException简称NPE)
         * Ran As Java Application:
         * Exception in thread "main" java.lang.NullPointerException
         *             at cointest.CoinTWR.main(CoinTWR.java:21)
         */
        try (InputStream i = null) {
            i.available();
        }

    }
    
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助