java中用try-with-resources关闭inputstream最安全简洁,它自动调用close()且不遗漏异常;inputstream及其子类均实现autocloseable,支持该语法,多资源按声明逆序关闭。

Java 中用 try-with-resources 关闭 InputStream 是最安全、简洁的方式,它能自动调用 close(),即使发生异常也不会遗漏。
必须实现 AutoCloseable 接口
InputStream 及其子类(如 FileInputStream、ByteArrayInputStream、BufferedInputStream)都实现了 AutoCloseable 接口,因此可以直接用于 try-with-resources 语句。
- 不用手动写
finally块或显式调用close() - 资源在 try 块结束时(无论是否抛异常)自动关闭
- 如果多个资源,按声明逆序关闭(后声明的先关),避免依赖问题
基本写法:单个 InputStream
直接在 try 后的括号中声明并初始化流:
try (InputStream is = new FileInputStream("data.txt")) {
int data;
while ((data = is.read()) != -1) {
System.out.write(data);
}
} catch (IOException e) {
// 处理读取或关闭过程中的异常
e.printStackTrace();
}
注意:is 在 try 块结束后自动关闭,无需也不应再调用 is.close()。
多个资源一起管理(如输入+输出)
可在同一 try 括号中声明多个资源,用分号分隔:
try (InputStream in = new FileInputStream("input.txt");
OutputStream out = new FileOutputStream("output.txt")) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
这里 out 先关闭,再关闭 in —— 符合资源释放顺序惯例,也避免输出未刷新就中断。
自定义 InputStream 也要支持自动关闭
如果你继承 InputStream 并添加了需要清理的资源(如本地句柄、缓冲区等),记得重写 close() 方法,并确保它真正释放资源:
public class MyInputStream extends InputStream {
private final SomeResource resource;
public MyInputStream(SomeResource r) {
this.resource = r;
}
@Override
public void close() throws IOException {
try {
resource.cleanup(); // 自定义清理逻辑
} finally {
super.close(); // 如果父类有可关闭行为,也调用
}
}
// ... 实现 read() 等抽象方法
}
这样它也能被 try-with-resources 正确管理。
不复杂但容易忽略:只要类型是 AutoCloseable,且你用的是 try-with-resources 声明方式,Java 就会保障关闭。别在 try 块里手动 close,也别把流声明在 try 外再传入——那会失去自动管理能力。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











