189 8069 5689

如何使用try-with-resource对io流进行关闭-创新互联

这篇文章给大家介绍如何使用try-with-resource对io流进行关闭,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

创新互联主要从事网站建设、网站设计、网页设计、企业做网站、公司建网站等业务。立足成都服务呈贡,10多年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792

传统写法操作io流

例如如下读取的文件的io流,我们之前可能会这样写

public class Main {
 public static void main(String[] args) {
  FileInputStream fileInputStream =null;
  try {
   fileInputStream = new FileInputStream(new File("/Users/laoniu/a.txt")); //打开流
   byte[] bytes = new byte[1024];
   int line = 0; 
   //读取数据
   while ((line = fileInputStream.read(bytes))!= -1){
    System.out.println(new String(bytes,0,line));
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  }finally {
   if (fileInputStream != null){ //不为空
    try {
     fileInputStream.close(); //关闭流
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

使用try-with-resource写法优雅操作io流

public class Main {
 public static void main(String[] args) {
  //把打开流的操作都放入try()块里
  try( FileInputStream fileInputStream = new FileInputStream(new File("/Users/laoniu/a.txt"))) {
   byte[] bytes = new byte[1024];
   int line = 0;
   while ((line = fileInputStream.read(bytes))!= -1){
    System.out.println(new String(bytes,0,line));
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

在try()中可以编写多个文件io流或网络io流。让我们看看java编译器是怎么帮我们实现的

借助idea查看编译后的代码

如何使用try-with-resource对io流进行关闭

可以看到编译后的代码,java编译器自动替我们加上了关闭流的操作。所以跟我们自己关闭流是一样的。try-with-resource这样优雅的写法还是不错的,让代码看起来不那么臃肿。

注意jdk1.7以后才可以用

关于如何使用try-with-resource对io流进行关闭就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


当前题目:如何使用try-with-resource对io流进行关闭-创新互联
文章地址:http://cdxtjz.cn/article/dhhjjo.html

其他资讯