Closeable
JDK7之前
JDK7之前的版本在釋放資源的時候,使用的try-catch-finally來操作資源。
其中,try代碼塊中使用獲取、修改資源,catch捕捉資源操作異常,finally代碼塊來釋放資源。
try {
fos = new FileOutputStream("test.txt");
dos = new DataOutputStream(fos);
dos.writeUTF("JDK7");
} catch (IOException e) {
// error處理
} finally {
fos.close();
dos.close();
}
問題來了,finally代碼塊中的fos.close()
出現了異常,將會阻止dos.close()
的調用,從而導致dos沒有正確關閉而保持開放狀態。
解決方法是把finally代碼塊中的兩個fos和dos的關閉繼續套在一個try-catch-finally代碼塊中。
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
fos = new FileOutputStream("test.txt")
dos = new DataOutputStream(fos);
// 寫一些功能
} catch (IOException e) {
// error處理
} finally {
try {
fos.close();
dos.close();
} catch (IOException e) {
// log the exception
}
}
JDK7及之後
JDK7之後有了帶資源的try-with-resource代碼塊,隻要實現了AutoCloseable或Closeable接口的類或接口,都可以使用該代碼塊來實現異常處理和資源關閉異常拋出順序。
try(FileOutputStream fos = new FileOutputStream("test.txt")){
// 寫一些功能
} catch(Exception e) {
// error處理
}
我們可以發現,在新版本的資源try-catch中,我們已經不需要對資源進行顯示的釋放,而且所有需要被關閉的資源都能被關閉。
需要注意的是,資源的close方法的調用順序與它們的創建順序是相反的。
最後更新:2017-08-21 19:02:15