今日代碼 PK | 使用 try-with-resources 關閉資源
try-with-resources 是 Java 7 中引入的一個語法糖,
用于自動關閉實現(xiàn)了 AutoCloseable 或 Closeable 接口的資源,
比如 文件輸入輸出流 等。
使用try-with-resources關閉資源非常方便,
示例代碼如下:
try (InputStream in = new FileInputStream("input.txt");
OutputStream out = new FileOutputStream("output.txt")) {
// 處理輸入輸出流
} catch (IOException e) {
e.printStackTrace();
}
如果不使用這種方式,那么就需要我們在 finally塊中手動處理,
示例代碼如下:
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("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();
}
}
可以明顯的發(fā)現(xiàn),下面這種方式更加繁瑣,也容易出現(xiàn)遺漏關閉資源的情況。
因此推薦大家使用try-with-resources方式來關閉資源。
大家更喜歡哪種呢?歡迎投票并在評論區(qū)留下自己的想法。
完整代碼片段來源于代碼小抄,歡迎點擊進入小程序閱讀!
在線訪問:https://www.codecopy.cn/post/umo6m1
更多優(yōu)質代碼歡迎進入小程序查看!
往期推薦
評論
圖片
表情
