前言

java的一大特性就是jvm会对内部资源实现自动回收,即自动gc,给开发者带来了极大的便利。但是jvm对外部资源的引用却无法自动回收,例如数据库连接,网络连接以及输入输出io流等,这些连接就需要我们手动去关闭,不然会导致外部资源泄露,连接池溢出以及文件被异常占用等。

传统的手动释放外部资源一般放在一般放在try{}catch(){}finally{}机制的finally代码块中,因为finally代码块中语句是肯定会被执行的,即保证了外部资源最后一定会被释放。同时考虑到finally代码块中也有可能出现异常,finally代码块中也有一个try{}catch(){},这种写法是经典的传统释放外部资源方法,显然是非常繁琐的。

传统写法操作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查看编译后的代码

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

注意jdk1.7以后才可以用

总结

到此这篇关于try-with-resource优雅关闭io流的文章就介绍到这了,更多相关try-with-resource优雅关闭io流内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!