天天看點

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;

fos = new FileOutputStream("test.txt")
dos = new DataOutputStream(fos);
// 寫一些功能           
// error處理           
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方法的調用順序與它們的建立順序是相反的。