最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用try-with-resource的輸入輸出流自動關閉

 更新時間:2021年07月31日 15:12:02   作者:wunlie  
這篇文章主要介紹了使用try-with-resource的輸入輸出流自動關閉方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

try-with-resource的輸入輸出流自動關閉

最近在做代碼審核的時候,審核工具提示我將 try-catch-finally 給替換掉,而且根據(jù)公司相關要求,該提示的級別還不低,不改不予通過。

先看看代碼吧:

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);
}

對比代碼,不難發(fā)現(xiàn),輸入輸出流的關閉存在著差異。難道輸入輸出流不用關閉了嗎?

帶著這個問題看看源代碼,發(fā)現(xiàn)

public class FileInputStream extends InputStream{}
public abstract class InputStream implements Closeable {}
/**
 * A {@code Closeable} is a source or destination of data that can be closed.
 * The close method is invoked to release resources that the object is
 * holding (such as open files).
 *
 * @since 1.5
 */
public interface Closeable extends AutoCloseable {}
/**
 * An object that may hold resources (such as file or socket handles)
 * until it is closed. The {@link #close()} method of an {@code AutoCloseable}
 * object is called automatically when exiting a {@code
 * try}-with-resources block for which the object has been declared in
 * the resource specification header. This construction ensures prompt
 * release, avoiding resource exhaustion exceptions and errors that
 * may otherwise occur.
 *
 * @apiNote
 * <p>It is possible, and in fact common, for a base class to
 * implement AutoCloseable even though not all of its subclasses or
 * instances will hold releasable resources.  For code that must operate
 * in complete generality, or when it is known that the {@code AutoCloseable}
 * instance requires resource release, it is recommended to use {@code
 * try}-with-resources constructions. However, when using facilities such as
 * {@link java.util.stream.Stream} that support both I/O-based and
 * non-I/O-based forms, {@code try}-with-resources blocks are in
 * general unnecessary when using non-I/O-based forms.
 *
 * @author Josh Bloch
 * @since 1.7
 */
public interface AutoCloseable {}

AutoCloseable 顧名思義, 自動關閉流. 從注釋中我們可以發(fā)現(xiàn),實現(xiàn)了AutoCloseable并在try()中聲明的對象,當try-with-resource代碼塊執(zhí)行完的時候,會自動調(diào)用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();
    }
   }
  }

上面是一段讀取文件內(nèi)容的示意代碼,為了防止在try代碼塊中出現(xiàn)異常后導致的資源泄露問題,在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();
  }

好了,上面已經(jīng)引入今天的主題,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();
  }
 }

執(zhí)行上面的代碼,由于MyResource的close方法中出現(xiàn)了異常,此時創(chuàng)建的MyResource1就不會被關閉,從而出現(xiàn)資源泄露情況,為了規(guī)避這個問題,為了規(guī)避這個問題,我們需要創(chuàng)建的實現(xiàn)AutoCloseable接口的對象單獨創(chuàng)建。

如下面所示:

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

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • Logback配置文件這么寫,還說你不會整理日志?

    Logback配置文件這么寫,還說你不會整理日志?

    logback框架會默認加載classpath下命名為logback-spring.xml或logback.xml的配置文件。這篇文章主要介紹了Logback配置文件寫法,需要的朋友可以參考下
    2020-07-07
  • 淺談SpringSecurity基本原理

    淺談SpringSecurity基本原理

    今天帶大家了解一下SpringSecurity的基本原理,文中有非常詳細的代碼示例,對正在學習java的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-05-05
  • Spring Cloud Config 使用本地配置文件方式

    Spring Cloud Config 使用本地配置文件方式

    這篇文章主要介紹了Spring Cloud Config 使用本地配置文件方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java如何使用正則表達式查找指定字符串

    Java如何使用正則表達式查找指定字符串

    在軟件開發(fā)中正則表達式是個很有用的功能,使用正則表達式可以簡化代碼,省去不少時間,下面這篇文章主要給大家介紹了關于Java如何使用正則表達式查找指定字符串的相關資料,需要的朋友可以參考下
    2022-09-09
  • Java中關于優(yōu)先隊列PriorityQueue的使用及相關方法

    Java中關于優(yōu)先隊列PriorityQueue的使用及相關方法

    這篇文章主要介紹了Java中關于優(yōu)先隊列PriorityQueue的使用及相關方法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • Mybatis實現(xiàn)查詢相冊數(shù)據(jù)列表流程講解

    Mybatis實現(xiàn)查詢相冊數(shù)據(jù)列表流程講解

    這篇文章主要介紹了Mybatis實現(xiàn)查詢相冊數(shù)據(jù)列表流程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧
    2022-12-12
  • JDBC三層架構深入刨析

    JDBC三層架構深入刨析

    三層架構是一種軟件設計架構,是一種組織代碼的手段和方法,三層架構的優(yōu)點是擴展性好,復用性高;缺點是步驟多,比較繁瑣;代碼多,效率降低
    2022-12-12
  • 詳解java中的static關鍵字

    詳解java中的static關鍵字

    這篇文章主要介紹了java中的static關鍵字的的相關資料,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-06-06
  • Swagger2配置Security授權認證全過程

    Swagger2配置Security授權認證全過程

    這篇文章主要介紹了Swagger2配置Security授權認證全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Java關鍵字之this用法詳解

    Java關鍵字之this用法詳解

    這篇文章將為大家詳細介紹一下Java關鍵字this的用法,文中有相關的代碼示例,希望對大家的學習或工作有一定的幫助,感興趣的同學可以參考下
    2023-05-05

最新評論

台东县| 图们市| 苍梧县| 冷水江市| 栖霞市| 六盘水市| 肇东市| 山东省| 合川市| 峨边| 阆中市| 巴楚县| 侯马市| 新宾| 潞西市| 大悟县| 水富县| 宁陕县| 柯坪县| 唐海县| 醴陵市| 清流县| 商都县| 关岭| 望城县| 阿荣旗| 南江县| 海安县| 绿春县| 五华县| 深泽县| 洞口县| 淮安市| 新蔡县| 蓝田县| 湖北省| 白朗县| 饶河县| 天台县| 蒲城县| 勐海县|