一、手动关闭

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~

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐