Java 自动关闭资源语法糖 - try-with-resources
前言
日常开发中,我们经常会看到如下代码:
try (InputStream is = new FileInputStream("example.txt")) {
byte[] bytes = InputStreamUtils.toByteArray(is);
// 处理字节数组
} catch (IOException e) {
e.printStackTrace();
}
在 Java 中,这种 try-with-resources 语句是一种用于自动关闭资源的语法糖,它能确保在代码执行完毕后,相关资源(如文件流、网络连接、数据库连接等)被正确关闭,从而避免资源泄漏。
优势
1、自动资源管理
传统的 try-catch-finally 需要手动在 finally 块中关闭资源,代码冗长且容易出错:
InputStream is = null;
try {
is = new FileInputStream("example.txt");
// 使用is读取文件
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close(); // 必须在finally中手动关闭
} catch (IOException e) {
e.printStackTrace();
}
}
}
而 try-with-resources 会自动调用资源的 close() 方法,无需手动编写 finally 块:
try (InputStream is = new FileInputStream("example.txt")) {
// 使用is读取文件(自动关闭)
} catch (IOException e) {
e.printStackTrace();
}
2、处理多重资源
当需要同时管理多个资源时(如输入流和输出流),try-with-resources 会按 逆序 自动关闭所有资源:
try (
FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt")
) {
// 使用fis和fos(自动关闭两个流)
} catch (IOException e) {
e.printStackTrace();
}
3、异常处理更健壮
传统写法中,如果 try 块和 finally 块都抛出异常,finally 块的异常会覆盖 try 块的异常,导致原始异常丢失。而 try-with-resources 会抑制资源关闭时的异常,并通过 getSuppressed() 方法保留所有异常信息。
4、适用条件
- 资源必须实现
AutoCloseable接口(如 InputStream、OutputStream、Connection 等)。 - 资源的
close()方法会被自动调用,无论是否发生异常。
总结
try (InputStream is = new FileInputStream(“example.txt”)) 的写法:
- 简化代码:无需手动编写 finally 块和 close() 调用。
- 防止资源泄漏:确保资源在使用后被正确关闭。
- 增强异常处理:保留完整的异常堆栈信息。

1281

被折叠的 条评论
为什么被折叠?



