java中io各种流的关闭顺序

本文详细阐述了如何管理并关闭流资源,包括资源释放、依赖关系处理及常见错误处理,确保程序稳定运行。

还是先看API

void close()
          Closes this stream and releases any system resources associated with it.
close
void close() throws IOException
Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.
Throws:
IOException - if an I/O error occurs
 

关闭该流并释放与之关联的所有资源。在关闭该流后,再调用 read()、ready()、mark()、reset() 或 skip() 将抛出 IOException。关闭以前关闭的流无效。

[html]
public void close() throws IOException { 
    synchronized (lock) { 
        if (in == null) 
        return; 
        in.close(); 
        in = null; 
        cb = null; 
    } 

一般情况下是:先打开的后关闭,后打开的先关闭

另一种情况:看依赖关系,如果流a依赖流b,应该先关闭流a,再关闭流b

例如处理流a依赖节点流b,应该先关闭处理流a,再关闭节点流b

当然完全可以只关闭处理流,不用关闭节点流。处理流关闭的时候,会调用其处理的节点流的关闭方法

如果将节点流关闭以后再关闭处理流,会抛出IO异常


### Java IO关闭的最佳实践 在Java中,正确关闭IO是一个重要的开发习惯,可以有效防止资源泄漏并提高程序稳定性。通常情况下,建议按照 **打开后关闭** 的原则来管理资源。 当存在多个嵌套的IO时(例如 `InputStreamReader` 包裹着 `FileInputStream`),应优关闭最外层的对象[^1]。这是因为大多数Java IO类实现了链式设计,在关闭外部时会自动触发内部关闭操作[^2]。然而,为了确保万无一失,推荐使用 try-with-resources 语句来简化资源管理过程[^4]。 #### 使用Try-With-Resources语法 自Java 7起引入的try-with-resources机制能够显著减少手动关闭的工作量,并保证即使发生异常也能安全释放资源。以下是具体代码示例: ```java import java.io.*; public class IoExample { public static void main(String[] args) { String filePath = "example.txt"; // Try-with-resources 自动关闭所有声明的资源 try (FileInputStream fis = new FileInputStream(filePath); BufferedInputStream bis = new BufferedInputStream(fis)) { int data; while ((data = bis.read()) != -1) { System.out.print((char) data); } } catch (FileNotFoundException e) { System.err.println("文件未找到:" + e.getMessage()); } catch (IOException e) { System.err.println("I/O 错误:" + e.getMessage()); } } } ``` 在此例子中,无论是否抛出异常,`bis` 和 `fis` 都会被自动关闭[^4]。 #### 手动关闭的情况 如果无法利用try-with-resources,则需要显式调用close方法,并将其置于finally块内以保障执行可靠性。需要注意的是,应该单独捕获每个close调用可能引发的IOException,以免掩盖其他更重要的异常信息[^4]。 ```java import java.io.*; public class ManualIoClose { public static void main(String[] args) { FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream("example.txt"); bis = new BufferedInputStream(fis); int data; while ((data = bis.read()) != -1) { System.out.print((char) data); } } catch (FileNotFoundException e) { System.err.println("文件未找到:" + e.getMessage()); } catch (IOException e) { System.err.println("I/O 错误:" + e.getMessage()); } finally { if (bis != null) { try { bis.close(); // 外部关闭即可 } catch (IOException ex) { System.err.println("BIS 关闭失败:" + ex.getMessage()); } } // 不必再额外关闭FIS,因为BIS已经包含了它 } } } ``` 以上两种方式均遵循了最佳实践标准,其中首选try-with-resources因其简洁性和安全性成为现代Java开发中的主做法[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值