Java使用 try-with-resources 实现自动关闭资源的方法

1、 在Java1.7之前,我们需要通过下面这种方法, 在finally中释放资源,这种方法有点繁琐。

 BufferedReader br = null;
    String str;
    try {
      br = new BufferedReader(new FileReader(""));
      while ((str = br.readLine()) != null) {
        System.out.println(str);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (br != null) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

2、在java1.7之后,可以使用try-with-resources实现自动关闭资源

try (BufferedReader br = new BufferedReader(new FileReader(""))) {
      while ((str = br.readLine()) != null) {
        System.out.println(str);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

这样看上去,是不是感觉代码干净了许多,当程序运行完离开try语句块时,( )里的资源就会被自动关闭。

但是try-with-resources还有几个关键点要记住:

①、try()里面的类,必须实现了AutoCloseable接口。
②、在try()代码中声明的资源被隐式声明为fianl。
③、使用分号分隔,可以声明多个资源。

3、自定义类并实现AutoCloseable接口

class TestAutoClosable implements AutoCloseable {

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

  public void test() {
    System.out.println("test");
  }
  
}

接下来我们测试下,我们写得自定义类

 try (BufferedReader br = new BufferedReader(new FileReader("E:/test.txt"));
       TestAutoClosable testAutoClosable = new TestAutoClosable()) {
      testAutoClosable.test();
    } catch (Exception e) {
      e.printStackTrace();
    }

当调用testAutoClosable.test()方法时,下面是控制台打印的:

test
close

可以看到资源被成功关闭。