广告
返回顶部
首页 > 资讯 > 后端开发 > Python >使用try-with-resource的输入输出流自动关闭
  • 225
分享到

使用try-with-resource的输入输出流自动关闭

2024-04-02 19:04:59 225人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

try-with-resource的输入输出流自动关闭 最近在做代码审核的时候,审核工具提示我将 try-catch-finally 给替换掉,而且根据公司相关要求,该提示的级别还不

try-with-resource的输入输出流自动关闭

最近在做代码审核的时候,审核工具提示我将 try-catch-finally 给替换掉,而且根据公司相关要求,该提示的级别还不低,不改不予通过。

先看看代码吧:


FileReader fr = null;  
BufferedReader br = null;
try {
    fr = new FileReader(fileName);
    br = new BufferedReader(fr);
    return br.readLine();
} catch (Exception e) {
    log.error("error:{}", e);
} finally {
  if (br != null) {
    try {
      br.close();
    } catch(IOException e){
      log.error("error:{}", e);
    }
  }
  if (fr != null ) {
    try {
      br.close();
    } catch(IOException e){
      log.error("error:{}", e);
    }
  }
}

审核工具给出的意见是 替换为:


try (
    FileReader fr = new FileReader(fileName);
    BufferedReader br = new BufferedReader(fr)
  ) {
    return br.readLine();
}catch (Exception e) {
    log.error("error:{}", e);
}

或者是:


try (
    BufferedReader br = new BufferedReader(new FileReader(fileName))
  ) { 
    // no need to name intermediate resources if you don't want to
    return br.readLine();
}
catch (Exception e) { 
    log.error("error:{}", e);
}

对比代码,不难发现,输入输出流的关闭存在着差异。难道输入输出流不用关闭了吗?

带着这个问题看看源代码,发现


public class FileInputStream extends InputStream{}
public abstract class InputStream implements Closeable {}

public interface Closeable extends AutoCloseable {}

public interface AutoCloseable {}

AutoCloseable 顾名思义, 自动关闭流. 从注释中我们可以发现,实现了AutoCloseable并在try()中声明的对象,当try-with-resource代码块执行完的时候,会自动调用close()方法。

注意:

一个 try-with-resources 语句可以像普通的 try 语句那样有 catch 和 finally 块。在try-with-resources 语句中, 任意的 catch 或者 finally 块都是在声明的资源被关闭以后才运行。

使用try-with-resource需要注意的地方

try-with-resource是jdk7引入的语法糖,可以简化Autocloseable资源类的关闭过程,

比如JDK7以前下面的代码:


 File file = new File("d:/tmp/1.txt");
  FileInputStream fis = null;
  try {
   fis = new FileInputStream(file);
   xxxxx
            xxxxx
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   if(fis != null){
    try {
     fis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }

上面是一段读取文件内容的示意代码,为了防止在try代码块中出现异常后导致的资源泄露问题,在finally代码块中一般处理资源的关闭事项。

JDK之后上面的代码就可以简化成下面的写法:


  File file = new File("d:/tmp/1.txt");
  try(FileInputStream fis = new FileInputStream(file);) {
   fis.read();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
  }

可以看出是简化了不少,之所以称之为语法糖,是因为编译成class文件后实际的代码就不是这样的了,编译过程中会自动添加资源的关闭处理。

上面的代码编译出的class文件使用javap进行反编译后是下面这样的


File file = new File("d:/tmp/1.txt"); 
  try {
   Throwable var2 = null;
   Object var3 = null;
 
   try {
    FileInputStream fis = new FileInputStream(file);
                xxx
                xxxx
   } catch (Throwable var12) {
    if (var2 == null) {
     var2 = var12;
    } else if (var2 != var12) {
     var2.addSuppressed(var12);
    } 
    throw var2;
   }
  } catch (IOException var13) {
   var13.printStackTrace();
  }

好了,上面已经引入今天的主题,try-with-resource,但是仍然有需要注意的地方。

比如下面的代码:


private static class MyResource implements AutoCloseable{ 
  private MyResource1 res;  
  public MyResource(MyResource1 res){
   this.res = res;
  }
  
  @Override
  public void close() throws Exception {
   System.out.println("MyResource自动关闭");
   Integer a = null;
   a.toString();
   this.res.close();
  }
 }
 
 private static class MyResource1 implements AutoCloseable{ 
  @Override
  public void close() throws Exception {
   System.out.println("MyResource1自动关闭");
  }
 } 
 
 @Test
 public void test() throws Exception{
  try(
    MyResource r = new MyResource(new MyResource1())){
   Integer a = null ;
   a.toString();
  }
 }

执行上面的代码,由于MyResource的close方法中出现了异常,此时创建的MyResource1就不会被关闭,从而出现资源泄露情况,为了规避这个问题,为了规避这个问题,我们需要创建的实现AutoCloseable接口的对象单独创建。

如下面所示:


  try(
    MyResource1 res= new MyResource1();
    MyResource r = new MyResource(res)){
   Integer a = null ;
   a.toString();
  }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: 使用try-with-resource的输入输出流自动关闭

本文链接: https://www.lsjlt.com/news/131574.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 使用try-with-resource的输入输出流自动关闭
    try-with-resource的输入输出流自动关闭 最近在做代码审核的时候,审核工具提示我将 try-catch-finally 给替换掉,而且根据公司相关要求,该提示的级别还不...
    99+
    2022-11-12
  • java中怎么使用try-with-resource实现输入输出流自动关闭
    本篇内容介绍了“java中怎么使用try-with-resource实现输入输出流自动关闭”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!tr...
    99+
    2023-06-20
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作