一、认识AutoCloseable
AutoCloseable接口位于java.lang包下,从JDK1.7开始引入。
1.在1.7之前,我们通过try{} finally{} 在finally中释放资源。
二、代码演示
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 }