1. 程式人生 > 程式設計 >Java使用 try-with-resources 實現自動關閉資源的方法

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

可以看到資源被成功關閉。

到此這篇關於Java使用 try-with-resources 實現自動關閉資源的方法的文章就介紹到這了,更多相關java 自動關閉資源內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!