今日代码 PK | 使用 try-with-resources 关闭资源

程序员鱼皮

共 2398字,需浏览 5分钟

 · 2024-04-12

try-with-resources 是 Java 7 中引入的一个语法糖,

用于自动关闭实现了 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();
    }
}

可以明显的发现,下面这种方式更加繁琐,也容易出现遗漏关闭资源的情况。

因此推荐大家使用try-with-resources方式来关闭资源。

大家更喜欢哪种呢?欢迎投票并在评论区留下自己的想法。

完整代码片段来源于代码小抄,欢迎点击进入小程序阅读!

在线访问:https://www.codecopy.cn/post/umo6m1

更多优质代码欢迎进入小程序查看!

往期推荐

今日代码 PK | 避免循环查库

今日代码 PK | 使用 Optional 判空

今日代码 PK | Java 使用正则表达式

今日代码 PK | 优雅统计耗时

今日代码 PK | 日期时间处理

浏览 6
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报