一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - 使用try-with-resource的輸入輸出流自動關閉

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

2021-11-01 10:50wunlie Java教程

這篇文章主要介紹了使用try-with-resource的輸入輸出流自動關閉方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

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

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

先看看代碼吧:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);
    }
  }
}

審核工具給出的意見是 替換為:

?
1
2
3
4
5
6
7
8
try (
    FileReader fr = new FileReader(fileName);
    BufferedReader br = new BufferedReader(fr)
  ) {
    return br.readLine();
}catch (Exception e) {
    log.error("error:{}", e);
}

或者是:

?
1
2
3
4
5
6
7
8
9
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);
}

對比代碼,不難發現,輸入輸出流的關閉存在著差異。難道輸入輸出流不用關閉了嗎?

帶著這個問題看看源代碼,發現

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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 顧名思義, 自動關閉流. 從注釋中我們可以發現,實現了AutoCloseable并在try()中聲明的對象,當try-with-resource代碼塊執行完的時候,會自動調用close()方法。

注意:

一個 try-with-resources 語句可以像普通的 try 語句那樣有 catch 和 finally 塊。在try-with-resources 語句中, 任意的 catch 或者 finally 塊都是在聲明的資源被關閉以后才運行。

使用try-with-resource需要注意的地方

try-with-resource是JDK7引入的語法糖,可以簡化Autocloseable資源類的關閉過程,

比如JDK7以前下面的代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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();
   }
  }
 }

上面是一段讀取文件內容的示意代碼,為了防止在try代碼塊中出現異常后導致的資源泄露問題,在finally代碼塊中一般處理資源的關閉事項。

JDK之后上面的代碼就可以簡化成下面的寫法:

?
1
2
3
4
5
6
7
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進行反編譯后是下面這樣的

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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();
  }

好了,上面已經引入今天的主題,try-with-resource,但是仍然有需要注意的地方。

比如下面的代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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();
  }
 }

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

如下面所示:

?
1
2
3
4
5
6
try(
  MyResource1 res= new MyResource1();
  MyResource r = new MyResource(res)){
 Integer a = null ;
 a.toString();
}

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:https://blog.csdn.net/wangjie_19920912/article/details/69501883

延伸 · 閱讀

精彩推薦
  • Java教程Java8中Stream使用的一個注意事項

    Java8中Stream使用的一個注意事項

    最近在工作中發現了對于集合操作轉換的神器,java8新特性 stream,但在使用中遇到了一個非常重要的注意點,所以這篇文章主要給大家介紹了關于Java8中S...

    阿杜7482021-02-04
  • Java教程升級IDEA后Lombok不能使用的解決方法

    升級IDEA后Lombok不能使用的解決方法

    最近看到提示IDEA提示升級,尋思已經有好久沒有升過級了。升級完畢重啟之后,突然發現好多錯誤,本文就來介紹一下如何解決,感興趣的可以了解一下...

    程序猿DD9332021-10-08
  • Java教程Java實現搶紅包功能

    Java實現搶紅包功能

    這篇文章主要為大家詳細介紹了Java實現搶紅包功能,采用多線程模擬多人同時搶紅包,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙...

    littleschemer13532021-05-16
  • Java教程xml與Java對象的轉換詳解

    xml與Java對象的轉換詳解

    這篇文章主要介紹了xml與Java對象的轉換詳解的相關資料,需要的朋友可以參考下...

    Java教程網2942020-09-17
  • Java教程Java BufferWriter寫文件寫不進去或缺失數據的解決

    Java BufferWriter寫文件寫不進去或缺失數據的解決

    這篇文章主要介紹了Java BufferWriter寫文件寫不進去或缺失數據的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望...

    spcoder14552021-10-18
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    這篇文章主要介紹了Java使用SAX解析xml的示例,幫助大家更好的理解和學習使用Java,感興趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程20個非常實用的Java程序代碼片段

    20個非常實用的Java程序代碼片段

    這篇文章主要為大家分享了20個非常實用的Java程序片段,對java開發項目有所幫助,感興趣的小伙伴們可以參考一下 ...

    lijiao5352020-04-06
  • Java教程小米推送Java代碼

    小米推送Java代碼

    今天小編就為大家分享一篇關于小米推送Java代碼,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧...

    富貴穩中求8032021-07-12
主站蜘蛛池模板: 久久亚洲高清观看 | 精品国产国产精2020久久日 | 日韩成片 | 日韩精品成人在线 | 国产精品免费看久久久香蕉 | 精品国产一区二区三区久久久蜜臀 | 男人猛激烈吃奶gif动态图 | 日韩精品视频在线观看免费 | 国产精品欧美一区二区 | 97青草| 欧美大陆日韩一区二区三区 | poren黑人 | 免费观看国产视频 | 男生操女生动态图 | 亚洲欧美一区二区三区在饯 | 成人午夜影院在线观看 | 国产精品青青在线观看香蕉 | fquer老师 | 极品91 | 亚州精品视频 | jazz中国女人护士 | 国产日韩欧美在线观看不卡 | aaa大片| 公交车揉捏大乳呻吟喘娇 | 99福利在线观看 | 亚洲福利区 | 国产日韩视频一区 | 日本视频一区在线观看免费 | 含羞草传媒每天免费一次破解 | 精品国产综合 | www免费插插视频 | 欧美二区视频 | 果冻传媒91 | 日韩欧美国产综合精品 | 国产成人精品免费视频软件 | 亚洲精品国产精麻豆久久99 | 91混血大战上海双胞胎 | 精品久久国产 | 互换娇妻爽文100系列小说 | 色人阁导航 | 好大好爽好硬 |