Java_jdk新特性try-with-resources

JDK7之前资源的关闭

public class CloseResourceBefore7 {
    private static final String FileName = "file.txt";

    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = null;

        try {
            inputStream = new FileInputStream(FileName);
            char c1 = (char) inputStream.read();
            System.out.println("c1=" + c1);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
}

JDK7及以后关闭资源的正确姿势:try-with-resource Resource的定义:所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。 简单Demo进行证实: 实现java.lang.AutoCloseable接口的Resource类:

public class Resource implements AutoCloseable {
    public void sayHello() {
        System.out.println("123");
    }

    @Override
    public void close() throws Exception {
        System.out.println("Resource is closed");
    }
}

测试类CloseResourceIn7.java

public class CloseResourceIn7 {
    public static void main(String[] args) {
        try(Resource resource = new Resource()) {
            resource.sayHello();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注:这样使用代码也可以写的很简洁,如果用jdk7之前的方式去关闭资源,那么资源越多,用fianl关闭资源时嵌套也就越多

发布了127 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/ZGL_cyy/article/details/104247593
今日推荐