java file需要关闭吗_Java语言中文件资源在不需要时就要关闭

文件处理案例:

以下代码打开了一个文件,但在使用完后没有去关闭这个文件

public int processFile(String fileName)                        throws IOException, FileNotFoundException {   FileInputStream stream = new FileInputStream(fileName);   BufferedReader bufRead =      new BufferedReader(new InputStreamReader(stream));   String line;   while ((line = bufRead.readLine()) != null) {     sendLine(line);   }   return 1; }

请给出可能的修改方案,以便相关的文件资源使用后能够正常地关闭及回收。

方案1:

为了释放文件资源,以便相关的文件资源使用后能够正常地关闭及回收,

释放所有请求的资源,不管任何可能异常发生,即使’  bufRead ’也可能导致异常。

FileInputStream 对象也按请求关闭。

try {   final FileInputStream stream = new FileInputStream(fileName);   try {     final BufferedReader bufRead =         new BufferedReader(new InputStreamReader(stream));     String line;     while ((line = bufRead.readLine()) != null) {       sendLine(line);     }    } finally {      if (stream != null) {       try {         stream.close();       } catch (IOException e) {         // forward to handler       }     }   } } catch (IOException e) {   // forward to handler }

方案2:使用Java S7:try-with-resources

使用 try-with-resources 语句, 在 Java SE 7中介绍的, 释放所有获取的资源,不管任何可能发生的异常.

try (FileInputStream stream = new FileInputStream(fileName);      BufferedReader bufRead =         new BufferedReader(new InputStreamReader(stream))) {   String line;   while ((line = bufRead.readLine()) != null) {     sendLine(line);   } } catch (IOException e) {   // forward to handler }

try-with-resources构建发送任何IOException的catch子句,它被转发到一个异常处理程序。这包括资源的分配过程中产生异常(即的FileInputStream或BufferedReader创建)。它还包括任何IOException异常抛出的while循环执行过程中。最后,它包括关闭bufread或流中产生任何IOException。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值