JAVA的一大特性就是JVM會對内部資源實作自動回收,即自動GC,給開發者帶來了極大的便利。但是JVM對外部資源的引用卻無法自動回收,例如資料庫連接配接,網絡連接配接以及輸入輸出IO流等,這些連接配接就需要我們手動去關閉,不然會導緻外部資源洩露,連接配接池溢出以及檔案被異常占用等。
傳統的手動釋放外部資源一般放在一般放在try{}catch(){}finally{}機制的finally代碼塊中,因為finally代碼塊中語句是肯定會被執行的,即保證了外部資源最後一定會被釋放。同時考慮到finally代碼塊中也有可能出現異常,finally代碼塊中也有一個try{}catch(){},這種寫法是經典的傳統釋放外部資源方法,顯然是非常繁瑣的。
傳統寫法操作io流
例如如下讀取的檔案的io流,我們之前可能會這樣寫
public class Main {
public static void main(String[] args) {
FileInputStream fileInputStream =null;
try {
fileInputStream = new FileInputStream(new File("/Users/laoniu/a.txt")); //打開流
byte[] bytes = new byte[1024];
int line = 0;
//讀取資料
while ((line = fileInputStream.read(bytes))!= -1){
System.out.println(new String(bytes,0,line));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileInputStream != null){ //不為空
try {
fileInputStream.close(); //關閉流
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
使用try-with-resource寫法優雅操作io流
public class Main {
public static void main(String[] args) {
//把打開流的操作都放入try()塊裡
try( FileInputStream fileInputStream = new FileInputStream(new File("/Users/laoniu/a.txt"))) {
byte[] bytes = new byte[1024];
int line = 0;
while ((line = fileInputStream.read(bytes))!= -1){
System.out.println(new String(bytes,0,line));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在try()中可以編寫多個檔案io流或網絡io流。讓我們看看java編譯器是怎麼幫我們實作的
借助idea檢視編譯後的代碼
可以看到編譯後的代碼,java編譯器自動替我們加上了關閉流的操作。是以跟我們自己關閉流是一樣的。try-with-resource這樣優雅的寫法還是不錯的,讓代碼看起來不那麼臃腫。
注意jdk1.7以後才可以用