使用AutoCloseable 实现自动关闭资源

一、认识AutoCloseable

AutoCloseable接口位于java.lang包下,从JDK1.7开始引入。

1.在1.7之前,我们通过try{} finally{} 在finally中释放资源。

在finally中关闭资源存在以下问题:
1、自己要手动写代码做关闭的逻辑;
2、有时候还会忘记关闭一些资源;
3、关闭代码的逻辑比较冗长,不应该是正常的业务逻辑需要关注的;
 
2.对于实现AutoCloseable接口的类的实例,将其放到try后面(我们称之为:带资源的try语句),在try结束的时候,会自动将这些资源关闭(调用close方法)。
 
带资源的try语句的3个关键点:
1、由带资源的try语句管理的资源必须是实现了AutoCloseable接口的类的对象。
2、在try代码中声明的资源被隐式声明为fianl。
3、通过使用分号分隔每个声明可以管理多个资源。

二、代码演示
 1 public class AutoCloseableDemo {
 2     public static void main(String[] args) {
 3         try (AutoCloseableObjecct app = new AutoCloseableObjecct()) {
 4             System.out.println("--执行main方法--");
 5         } catch (Exception e) {
 6             System.out.println("--exception--");
 7         } finally {
 8             System.out.println("--finally--");
 9         }
10     }
11 
12     //自己定义类 并实现AutoCloseable
13     public static class AutoCloseableObjecct implements AutoCloseable {
14         @Override
15         public void close() throws Exception {
16             System.out.println("--close--");
17         }
18 
19     }
20 
21 
22     @Test
23     public void demo2() {
24 
25         //JDK1.7之前,释放资源方式
26         FileInputStream fileInputStream = null;
27         try {
28             fileInputStream = new FileInputStream("");
29         } catch (FileNotFoundException e) {
30             e.printStackTrace();
31         } finally {
32             try {
33                 fileInputStream.close();
34             } catch (IOException e) {
35                 e.printStackTrace();
36             }
37         }
38 
39         //1.7之后,只要实现了AutoCloseable接口
40         try (FileInputStream fileInputStream2 = new FileInputStream("")) {
41 
42         } catch (FileNotFoundException e) {
43             e.printStackTrace();
44         } catch (IOException e) {
45             e.printStackTrace();
46         }
47 
48     }
49 
50 }

  

原文地址:https://www.cnblogs.com/756623607-zhang/p/9216091.html