答案:try-with-resources可自动关闭实现AutoCloseable接口的资源,简化代码并防止泄漏。其语法在try后括号内声明资源,执行完毕后自动调用close方法。支持单个或多个资源管理,关闭顺序与声明顺序相反。可用于BufferedReader、FileWriter等场景,自定义资源需实现AutoCloseable接口。若try块和close均抛异常,try异常为主,close异常被压制且可通过getSuppressed获取。

在Java中,try-with-resources 是一种自动管理资源的机制,它能确保实现了 AutoCloseable 接口的资源在使用完毕后自动关闭,无需手动调用 close() 方法。这不仅简化了代码,也有效避免了资源泄漏。
try-with-resources 的语法是在 try 后面的小括号中声明并初始化资源,这些资源会在 try 块执行结束后自动关闭。
try (资源声明和初始化) {
// 使用资源
} catch (异常类型 变量) {
// 异常处理(可选)
} finally {
// 最终操作(可选)
}
只要资源实现了 AutoCloseable 或 Closeable 接口,就可以用于 try-with-resources。
以下是一些典型的使用场景:
立即学习“Java免费学习笔记(深入)”;
1. 读取文件内容(使用 BufferedReader)
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("读取文件时出错:" + e.getMessage());
}
在这个例子中,BufferedReader 会自动关闭,无需在 finally 块中显式调用 br.close()。
2. 写入文件(使用 FileWriter)
try (FileWriter fw = new FileWriter("output.txt")) {
fw.write("Hello, try-with-resources!");
} catch (IOException e) {
System.err.println("写入文件失败:" + e.getMessage());
}
FileWriter 在 try 块结束时自动关闭,系统会刷新缓冲区并释放文件句柄。
3. 多个资源同时管理
try (
FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt")
) {
int data;
while ((data = fis.read()) != -1) {
fos.write(data);
}
} catch (IOException e) {
System.err.println("复制文件出错:" + e.getMessage());
}
多个资源用分号隔开,关闭顺序与声明顺序相反——先声明的后关闭。
如果你自己创建的类需要支持自动关闭,只需实现 AutoCloseable 接口即可。
public class MyResource implements AutoCloseable {
public MyResource() {
System.out.println("资源已打开");
}
public void doWork() {
System.out.println("正在工作...");
}
@Override
public void close() {
System.out.println("资源已关闭");
}
}
使用方式:
try (MyResource resource = new MyResource()) {
resource.doWork();
}
输出结果会显示:先“资源已打开”,再“正在工作...”,最后“资源已关闭”。
如果 try 块和 close() 方法都抛出异常,JVM 会将 try 块中的异常作为主要异常抛出,而 close() 中的异常会被压制(suppressed),但可以通过 Throwable.getSuppressed() 获取。
基本上就这些。try-with-resources 让资源管理变得更安全、简洁,推荐在所有适用场景中优先使用。
以上就是在Java中如何使用try-with-resources自动关闭资源的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号