一、認識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 }