关于io操作关闭的几种方式

3 篇文章 0 订阅

一、手动关闭

FileInputStream is = null;
try {
    is = new FileInputStream(new File(""));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (null != is) {
            is.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

二、通过工具类关闭, 例如 Apache的IOUtils

FileInputStream is = null;
try {
    is = new FileInputStream(new File(""));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    IOUtils.closeQuietly(is);
}

需要引入commons-io 依赖

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

三、通过JDK7的新特性 try-with-resource

参考资料: http://www.kissyu.org/2016/10/06/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3Java%20try-with-resource/

try (FileInputStream is = new FileInputStream(new File(""))) {
    // do something
} catch (Exception e) {
    e.printStackTrace();
}

四、通过Lombok的 @Cleanup

参考资料: https://blog.csdn.net/qq_38288606/article/details/80690827

try {
    @Cleanup FileInputStream is = new FileInputStream(new File(""));
} catch (Exception e) {
    e.printStackTrace();
}

需要引入lombok依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.4</version>
    <scope>provided</scope>
</dependency>

idea需要安装lombok插件支持, 插件库搜索 lombok进行安装并重启即可使用

如果帮到你,请点个赞吧 O(∩_∩)O~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值