java中try-with-resources可自动关闭autocloseable资源,如inputstream等,避免手动close导致的泄漏;资源按声明逆序关闭,关闭异常被抑制并可通过getsuppressed()获取;自定义资源只需实现autocloseable接口。

Java 中使用 try-with-resources 可以自动关闭实现了 AutoCloseable 接口的资源(如 InputStream、OutputStream、Reader、Writer 等),避免手动调用 close(),大幅降低资源泄漏风险。
确保资源类型支持 AutoCloseable
Java 标准 IO 类基本都实现了 AutoCloseable(JDK 7+),包括:
-
FileInputStream/FileOutputStream -
BufferedInputStream/BufferedOutputStream -
InputStreamReader/OutputStreamWriter -
FileReader/FileWriter -
Scanner(包装了可关闭的底层流时)
只要资源在 try 括号内声明并初始化,JVM 就会在 try 块结束(无论正常退出还是异常抛出)后自动调用其 close() 方法。
正确写法:资源声明放在 try 后的圆括号中
资源必须是 final 或等效 final(即声明后不重新赋值),且需显式初始化:
Java JDK 25 来自 OpenJDK 官方归档,版本为 JDK 25,本条下载地址已指向官方 Windows x64 zip 安装包直链,适合调试旧项目或兼容旧版 Java 运行环境。
try (FileInputStream fis = new FileInputStream("input.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream("output.txt")) {
// 读写操作
int b;
while ((b = bis.read()) != -1) {
fos.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
注意:多个资源用分号分隔,关闭顺序与声明顺序相反(后声明的先关闭),这符合“后开先关”原则,比如缓冲流应比底层流先关闭。
捕获并处理关闭异常(Suppressed Exception)
如果 try 块中抛出异常,且资源关闭时也发生异常,后者会被“抑制”(suppressed),并可通过 Throwable.getSuppressed() 获取。默认情况下,主异常仍被抛出,关闭异常不会掩盖它:
- 无需额外 try-catch 包裹 close —— JVM 自动处理
- 若需日志记录关闭失败,可在 catch 块中检查
e.getSuppressed() - 避免在 finally 里再手动 close,否则可能触发
IllegalStateException(已关闭)
自定义资源类也要实现 AutoCloseable
如果你封装了自己的 IO 资源类,只需实现 AutoCloseable 并提供无参 close() 方法即可参与 try-with-resources:
public class MyResource implements AutoCloseable {
private final InputStream is;
public MyResource(String path) throws IOException {
this.is = new FileInputStream(path);
}
@Override
public void close() throws IOException {
if (is != null) is.close();
}
}
// 使用方式
try (MyResource res = new MyResource("data.txt")) {
// 使用 res
}
这样就能和其他标准流一样,享受自动关闭的便利性和安全性。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










