像诗一样优雅的try-with-resource

239 阅读1分钟

工作了这么多年,还不知道try-with-resource?

作者Lucas

虽然你现在或许正在用JDK8,也或许你正在用JDK11,但你知道吗?在JDK7的时候引入了 一个新语句与用法呢?那就是try-with-resources。

JDK7之前

public static void main(String[] args) {
     FileInputStream fileInputStream =null;
     try {
         fileInputStream = new FileInputStream(new File("content.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();
             }
         }
     }
 }

JDK7之后

public static void main(String[] args) {
       /**
       *打开流的操作,我们放在try里面
       */
       try( FileInputStream fileInputStream = new FileInputStream(new File("content.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();
       }
   }

这样Java编译器就自动帮我们关闭了流