JDK1.7的资源关闭方式 try-with-resource

Java 7引入的新语法 try(resource)

当一个外部资源的句柄对象(比如FileInputStream对象)实现了AutoCloseable接口 就可以使用 try-with-resource 新的方式

将外部资源的句柄对象的创建放在try关键字后面的括号中,当这个try-catch代码块执行完毕后,Java会确保外部资源的close方法被调用。

新的方式

 try (InputStream input = new FileInputStream("properties/custom.properties")) {
            int n;
            while ((n = input.read()) != -1) {
                System.out.println(n);
            }
        } // 编译器在此自动为我们写入finally并调用close()

以前的方式

         InputStream input = null;
            try {
                input = new FileInputStream("properties/custom.properties");
                int n;
                while ((n = input.read()) != -1) { // 利用while同时读取并判断
                    System.out.println(n);
                }
            } finally {
                if (input != null) { input.close(); }
            }

try-with-resource并不是JVM虚拟机的新增功能,当你将上面代码反编译后会发现,其实对JVM虚拟机而言,它看到的依然是之前的写法。

 

posted @ 2020-02-08 14:41  Angry-rookie  阅读(309)  评论(0)    收藏  举报