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以后才可以用
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/242378.html
標籤:java
