網頁

2020/4/12

Java 使用 try-with-resources 關閉資源

Java 繼承Closeable介面的類別在操作結束時都應該呼叫close()關閉資源,在Java 7新增了try-with-resources語法,使得關閉資源的程式變得簡潔許多。

Java 7的try-with-resources用法如下,以OutputStream寫出文字檔為例。

String content = "hello world";
String pathName = "D:" + File.separator + "test.txt"; // D:\test.txt
File file = new File(pathName);

try ( // try-with-resources
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
) {
    bos.write(content.getBytes());
} catch (IOException e) {
    e.printStackTrace();
}

try關鍵字後的括弧即為try-with-resources block。在try()中開啟的資源在try-catch區塊中執行結束或發生錯誤都會自動關閉資源。

繼承AutoCloseable介面的物件才能放在try-with-resources block,而所有的Closeable皆同時為AutoCloseable


而在Java 7之前,關閉資源需在finally區塊中手動呼叫close()關閉,比較囉嗦麻煩。

String content = "hello world";
String pathName = "D:" + File.separator + "test.txt";
File file = new File(pathName);
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
    fos = new FileOutputStream(file);
    bos = new BufferedOutputStream(fos);
    bos.write(content.getBytes());
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (bos != null) {
        try {
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

沒有留言:

張貼留言