Java多资源嵌套关闭只需在try-with-resources括号中用分号分隔声明,按声明逆序自动关闭;所有资源须实现AutoCloseable接口,不可手动调用close(),异常时会抑制close异常并可通过getSuppressed()获取。

Java 中多资源嵌套关闭,直接在 try-with-resources 的括号里按顺序声明多个资源即可,它们会按**声明的逆序**自动关闭,无需手动嵌套 try 或调用 close()。
基本写法:逗号分隔多个资源
所有资源必须实现 AutoCloseable 接口(如 InputStream、Connection、Statement、ResultSet 等),并在 try 后的括号中用分号分隔:
try (FileInputStream fis = new FileInputStream("a.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis)) {
// 使用 dis 读取数据
int data = dis.readInt();
} // dis、bis、fis 按此逆序自动关闭
注意资源关闭顺序和依赖关系
虽然可以声明有依赖关系的资源(如 bis 包裹 fis),但 try-with-resources **不关心逻辑嵌套**,只按声明顺序逆序关闭:
- 先声明 fis → 最后关闭 fis
- 再声明 bis → 中间关闭 bis
- 最后声明 dis → 最先关闭 dis
这种顺序通常符合预期(子流先关,底层流后关),但需确保被包装资源(如 fis)在包装流(如 bis)关闭后仍可安全关闭 —— 标准 JDK 流类已处理这点,一般无需额外干预。
立即学习“Java免费学习笔记(深入)”;
避免重复关闭或关闭已关闭资源
不要在 try 块内手动调用 close(),否则可能触发重复关闭异常(如 IOException: Stream closed):
- ❌ 错误:在 try 块里写
bis.close() - ✅ 正确:完全交给 try-with-resources 管理
如果某资源不能被自动关闭(比如它由外部管理),不应放入 try-with-resources 括号中,而应单独处理。
异常抑制(Suppressed Exception)机制
当 try 块抛出异常,且多个资源 close() 也抛异常时,只有 try 块的异常被抛出,其余 close 异常会被“抑制”并可通过 Throwable.getSuppressed() 获取:
try (Resource r1 = new Resource();
Resource r2 = new Resource()) {
throw new RuntimeException("main exception");
} catch (RuntimeException e) {
Throwable[] suppressed = e.getSuppressed();
System.out.println("Suppressed: " + suppressed.length); // 可能为 2
}


















