java 中正确关闭流的最佳实践是使用 try-with-resources 语句,它会自动调用流的 close() 方法并处理异常。对于字节流(如 fileinputstream)和字符流(如 filereader),只需在 try 括号中声明流对象,无需手动编写关闭逻辑,从而避免资源泄漏和未捕获的 ioexception。

try-with-resources 如何自动管理资源生命周期
该机制依赖于 AutoCloseable 接口,所有标准 IO 流都实现了此接口。当 try 块执行完毕或抛出异常时,JVM 会按声明顺序逆序调用 close()。若关闭过程中发生异常,它们会被抑制而非覆盖主异常,确保程序稳定性。

import java.io.*;
public class StreamDemo {
public static void main(String[] args) {
// 使用 try-with-resources 自动关闭流
try (FileInputStream fis = new FileInputStream("data.txt");
BufferedInputStream bis = new BufferedInputStream(fis)) {
int data;
while ((data = bis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
System.err.println("读取失败: " + e.getMessage());
}
// 此处 fis 和 bis 已自动关闭
}
}预期输出:控制台打印 data.txt 内容,若无文件则打印错误信息。流在 try 块结束后自动释放系统资源,无需显式调用 close()。
立即学习“Java免费学习笔记(深入)”;
传统 finally 块关闭流的缺陷与风险
在 Java 7 之前,开发者需在 finally 块中手动关闭流。这种方式代码冗长,且若 close() 本身抛出异常,可能掩盖原始异常。此外,嵌套流关闭时需仔细处理每个流的异常,容易遗漏或重复关闭。

import java.io.*;
public class LegacyStreamDemo {
public static void main(String[] args) {
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream("data.txt");
bis = new BufferedInputStream(fis);
int data;
while ((data = bis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
System.err.println("读取失败: " + e.getMessage());
} finally {
// 手动关闭,需分别处理异常
if (bis != null) {
try { bis.close(); } catch (IOException e) { e.printStackTrace(); }
}
if (fis != null) {
try { fis.close(); } catch (IOException e) { e.printStackTrace(); }
}
}
}
}预期输出:与 try-with-resources 相同,但代码更复杂。若 close() 失败,异常被单独捕获,可能丢失原始 read() 异常信息。
关闭流时是否需要考虑输入流的空值情况
在 try-with-resources 中,即使流初始化为 null,也不会触发 close() 调用,因此安全。但若流对象在 try 声明前已赋值,需确保其非空以避免 NullPointerException。传统方式中,必须检查 null 再关闭,否则直接调用 close() 会抛异常。


















