當前位置: 妍妍網 > 碼農

今日程式碼 PK | 使用 try-with-resources 關閉資源

2024-03-22碼農

try-with-resources Java 7 中引入的一個語法糖,

用於自動關閉實作了 AutoCloseable Closeable 介面的資源,

比如 檔輸入輸出流 等。

使用 try-with-resources 關閉資源非常方便,

範例程式碼如下:

try (InputStreamin = newFileInputStream("input.txt");
OutputStreamout = newFileOutputStream("output.txt")) {
// 處理輸入輸出流
catch (IOException e) {
e.printStackTrace();
}

如果不使用這種方式,那麽就需要我們在 finally 塊中手動處理,

範例程式碼如下:

InputStreamin = null;
OutputStreamout = null;
try {
in = newFileInputStream("input.txt");
out = newFileOutputStream("output.txt");
// 處理輸入輸出流
catch (IOException e) {
e.printStackTrace();
finally {
try {
if (in != null) {
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null) {
out.close();
}
catch (IOException e) {
e.printStackTrace();
}
}

可以明顯的發現,下面這種方式更加繁瑣,也容易出現遺漏關閉資源的情況。

因此推薦大家使用 try-with-resources 方式來關閉資源。

大家更喜歡哪種呢?歡迎投票並在評論區留下自己的想法。

完整程式碼片段來源於程式碼小抄,歡迎點選進入小程式閱讀!

線上存取:https://www.codecopy.cn/post/umo6m1

更多優質程式碼歡迎進入小程式檢視!

往期推薦