例子:往一個文件內寫東西
以前的寫法,總是在流處理的最后都需要finally關閉資源,這樣多了就會覺得很麻煩
private static void oldtest(String filePath) throws FileNotFoundException { OutputStream out = new FileOutputStream(filePath); try { out.write((filePath+"我就是測試下用Java寫點東西進來").getBytes()); }catch (Exception e){ e.printStackTrace(); }finally { try { out.close(); }catch (Exception e){ e.printStackTrace(); } } }
Java7 里的try...catch...resource 寫法可以流會自動回收,只需在try()括號里寫流對象,這樣就不用老是finally了
//自動關閉資源寫法 private static void newtest(String filePath) throws FileNotFoundException { try(OutputStream out = new FileOutputStream(filePath);){ out.write("用try...catch..resource寫法試試會不會自動關閉資源".getBytes()); }catch (Exception e){ e.printStackTrace(); } }
我們可以看下源代碼:
這個outputStream實現了Closeable這個類,看下Closeable源代碼
看下AutoCloseable源代碼:
注意:
1、使用該寫法,需要該類有有實現AutoCloseable類
2、實現了AutoCloseable接⼝的類,在try()⾥聲明該類實例的時候,try結束后⾃動調⽤的 close⽅法,這個動作會早於finally⾥調⽤的⽅法
3、不管是否出現異常,try()⾥的實例都會被調⽤close⽅法
4、try⾥⾯可以聲明多個⾃動關閉的對象,越早聲明的對象,會越晚被close掉