zoukankan      html  css  js  c++  java
  • 使用try-with-resources偷懒关闭资源

    JDK1.7之后,引入了try-with-resources,使得关闭资源操作无需层层嵌套在finally中,代码简洁不少,本质是一个语法糖,能够使用try-with-resources关闭资源的类,必须实现AutoCloseable接口。

    1.7版本之前,传统的关闭资源操作如下:

     1 public static void main(String[] args){
     2 
     3     FileInputStream fileInputStream = null;
     4     try {
     5         fileInputStream = new FileInputStream("file.txt");
     6         fileInputStream.read();
     7     } catch (IOException e) {
     8         e.printStackTrace();
     9     }finally {
    10         try {
    11             assert fileInputStream != null;
    12             fileInputStream.close();
    13         } catch (IOException e) {
    14             e.printStackTrace();
    15         }
    16     }
    17 }

    可以看到,为了确保资源关闭正常,需要finall中再嵌入finally,try中打开资源越多,finall嵌套越深,可能会导致关闭资源的代码比业务代码还要多。

      但是使用了try-with-resources语法后,上面的例子可改写为:

    1 try(FileInputStream fileInputStream1 = new FileInputStream("file.txt")){     
    2     fileInputStream1.read();
    3 } catch (IOException e) {
    4     e.printStackTrace();
    5 }

    这是try-with-resources语句的结构,在try关键字后面的( )里new一些需要自动关闭的资源。

    try-with-resources语句能放多个资源

    1 try (ZipFile zf = new ZipFile(zipFileName);
    2      BufferedWriter writer = newBufferedWriter(outputFilePath, charset)
    3     ) {
    4 //执行任务
    5 }
  • 相关阅读:
    .net注册iis
    hdu 1081To The Max
    hdu 1312Red and Black
    hdu 1016Prime Ring Problem
    hdu 1159Common Subsequence
    hdu 1372Knight Moves
    hdu 1686Oulipo
    hdu 1241Oil Deposits
    hdu 1171Big Event in HDU
    hdu 4006The kth great number
  • 原文地址:https://www.cnblogs.com/qiaoxin11/p/12566569.html
Copyright © 2011-2022 走看看