使用try-with-resources注意的问题

package coin;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * 使用 try-with-resources 特性要注意的问题,在某些情况下资源可能无法关闭。
 * 要确保 try-with-resources 生效,正确的用法是为了各个资源声明独立变量。
 * @author Felix
 *
 */

public class TWRDemo {

    public static void main(String[] args) {

        // 下面的代码如果从文件(someFile.bin)创建ObjectInputStream时出错,
        // FileInputStream 可能就无法正确关闭。
        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream("someFile.in"))) {
            ...
        }
        
        //要确保 try-with-resources 生效,正确的用法是为了各个资源声明独立变量。
        try(FileInputStream fin = new FileInputStream("someFile.bin");
                ObjectInputStream in = new ObjectInputStream(fin)) {
            ...
        }    
    }

}
原文地址:https://www.cnblogs.com/IcanFixIt/p/4690603.html