try-with-resources

try-with-resources 是 JDK 7 中一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。资源(resource)是指在程序完成后,必须关闭的对象。try-with-resources 语句确保了每个资源在语句结束时关闭。所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。


传统写法:try-catch-finally

java 复制代码
public static void main(String[] args) {
    BufferedInputStream bin = null;
    BufferedOutputStream bout = null;
    try {
        bin = new BufferedInputStream(new FileInputStream(new File("")));
        bout = new BufferedOutputStream(new FileOutputStream(new File("")));
        while ((b = bin.read()) != -1) {
            bout.write(b);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bin != null) {
            try {
                bin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

JDK 7:try-with-resources

java 复制代码
public static void main(String[] args) {
    try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("")));
         BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("")))) {
        while ((b = bin.read()) != -1) {
            bout.write(b);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

JDK 9:

try-with-resources 声明在 JDK 9 已得到改进。如果你已经有一个资源是 final 或等效于 final 变量,您可以在 try-with-resources 语句中使用该变量,而无需在 try-with-resources 语句中声明一个新变量。

java 复制代码
public static void main(String[] args) throws Exception {
    BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("")));
    BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("")));
    try (bin;bout) {
        while ((b = bin.read()) != -1) {
            bout.write(b);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

资源必须实现 AutoClosable 接口,并重写 close 方法

java 复制代码
public class Connection implements AutoCloseable {
	@Override
	public void close(){
	}
}
相关推荐
野生技术架构师37 分钟前
2026 Java 面试全套总结,八股 + 场景 + AI 相关面试考点
java·人工智能·面试
香吧香1 小时前
java服务异常日志只打印异常类型,没有堆栈定位分析
java·jvm·异常
qq_2518364572 小时前
AI 疾病自查功能SpringbootAI项目实战 · 技术实现文档
java·ai·ai编程
逆境不可逃2 小时前
Pi Agent 学习笔记:对话太长以后,如何压缩上下文
java
MetaLite2 小时前
JDK 8~26 核心特性一览:从 Stream 到 Scoped Values
java
wno7043 小时前
Spring Boot WebFlux增删改查
java·spring boot·后端
君顾13 小时前
上海24小时自助健身房系统开发实战指南:从架构设计到落地部署
java·开发语言·健身房
SL_staff4 小时前
别急着买商业规则引擎:90%风控场景根本不需要全量编码能力
java·程序员·groovy
ManageEngineITSM5 小时前
DevOps和ITIL是什么关系?是替代还是互补一文讲清
java·服务器·资产管理·变更管理
SL_staff5 小时前
ERP排程总在纸上谈兵?JVS-APS如何用真实产能约束打通计划与执行闭环
java·人工智能·开源