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

一、手动关闭

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 依赖


    commons-io
    commons-io
    2.4

三、通过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依赖


    org.projectlombok
    lombok
    1.18.4
    provided

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

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

你可能感兴趣的:(idea,Java)