高效Java之try-with-resources

一些由Java類庫提供的可以通過close方法手動關閉的資源,例如inputStream類型,java.sql.Connection類型的資源。爲了避免使用者忘記關閉資源,或者多個資源的使用導致try-finally的嵌套,這種場景使用try-with-resources是更好的選擇:

// try-with-resources on multiple resources - short and sweet
static void copy(String src, String dst) throws IOException {
    try (InputStream   in = new FileInputStream(src);
         OutputStream out = new FileOutputStream(dst)) {
        byte[] buf = new byte[BUFFER_SIZE];
        int n;
        while ((n = in.read(buf)) >= 0)
            out.write(buf, 0, n);
    }
}

// try-with-resources with a catch clause(帶catch的使用)
static String firstLineOfFile(String path, String defaultVal) {
    try (BufferedReader br = new BufferedReader(
           new FileReader(path))) {
        return br.readLine();
    } catch (IOException e) {
        return defaultVal;
    }
}

當資源的調用出現異常,資源的關閉也出現異常時try-with-resources能抑制close時的異常,而try-finally會抑制第一個異常,導致錯誤難以排查。

需要注意的是:使用try-with-resources必須要繼承AutoCloseable接口(Java類庫與第三方類庫中的類中部分資源實現了該接口),按文字理解 流、連接、管道應該都實現了該接口,而ReentrantLock類型的資源由於沒有關閉的概念(需要釋放),不能使用try-with-resources

發佈了30 篇原創文章 · 獲贊 3 · 訪問量 8865
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章