免费观看又色又爽又黄的小说免费_美女福利视频国产片_亚洲欧美精品_美国一级大黄大色毛片

如何在Java中使用try-with-resource語句-創新互聯

如何在Java中使用try-with-resource語句?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。

專注于為中小企業提供成都做網站、成都網站制作、成都外貿網站建設服務,電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業上林免費做網站提供優質的服務。我們立足成都,凝聚了一批互聯網行業人才,有力地推動了1000+企業的穩健成長,幫助中小企業通過網站建設實現規模擴充和轉變。
public class Demo {
  public static void main(String[] args) {
    BufferedInputStream bin = null;
    BufferedOutputStream bout = null;
    try {
      bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
      bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")));
      int b;
      while ((b = bin.read()) != -1) {
        bout.write(b);
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      if (bin != null) {
        try {
          bin.close();
        }
        catch (IOException e) {
          e.printStackTrace();
        }
        finally {
          if (bout != null) {
            try {
              bout.close();
            }
            catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }
    }
  }
}

Oh My God!!!關閉資源的代碼竟然比業務代碼還要多!!!這是因為,我們不僅需要關閉BufferedInputStream,還需要保證如果關閉BufferedInputStream時出現了異常, BufferedOutputStream也要能被正確地關閉。所以我們不得不借助finally中嵌套finally大法。可以想到,打開的資源越多,finally中嵌套的將會越深!!!

更為可惡的是,Python程序員面對這個問題,竟然微微一笑很傾城地說:“這個我們一點都不用考慮的嘞~”:

但是兄弟莫慌!我們可以利用Java 1.7中新增的try-with-resource語法糖來打開資源,而無需碼農們自己書寫資源來關閉代碼。媽媽再也不用擔心我把手寫斷掉了!我們用try-with-resource來改寫剛才的例子:

public class TryWithResource {
  public static void main(String[] args) {
    try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
       BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
      int b;
      while ((b = bin.read()) != -1) {
        bout.write(b);
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

是不是很簡單?是不是很刺激?再也不用被Python程序員鄙視了!好了,下面將會詳細講解其實現原理以及內部機制。

動手實踐

為了能夠配合try-with-resource,資源必須實現AutoClosable接口。該接口的實現類需要重寫close方法:

public class Connection implements AutoCloseable {
  public void sendData() {
    System.out.println("正在發送數據");
  }
  @Override
  public void close() throws Exception {
    System.out.println("正在關閉連接");
  }
}

調用類:

public class TryWithResource {
  public static void main(String[] args) {
    try (Connection conn = new Connection()) {
      conn.sendData();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

運行后輸出結果:

正在發送數據
正在關閉連接

通過結果我們可以看到,close方法被自動調用了。

原理

那么這個是怎么做到的呢?我相信聰明的你們一定已經猜到了,其實,這一切都是編譯器大神搞的鬼。我們反編譯剛才例子的class文件:

public class TryWithResource {
  public TryWithResource() {
  }
  public static void main(String[] args) {
    try {
      Connection e = new Connection();
      Throwable var2 = null;
      try {
        e.sendData();
      } catch (Throwable var12) {
        var2 = var12;
        throw var12;
      } finally {
        if(e != null) {
          if(var2 != null) {
            try {
              e.close();
            } catch (Throwable var11) {
              var2.addSuppressed(var11);
            }
          } else {
            e.close();
          }
        }
      }
    } catch (Exception var14) {
      var14.printStackTrace();
    }
  }
}

看到沒,在第15~27行,編譯器自動幫我們生成了finally塊,并且在里面調用了資源的close方法,所以例子中的close方法會在運行的時候被執行。

異常屏蔽

我相信,細心的你們肯定又發現了,剛才反編譯的代碼(第21行)比遠古時代寫的代碼多了一個addSuppressed。為了了解這段代碼的用意,我們稍微修改一下剛才的例子:我們將剛才的代碼改回遠古時代手動關閉異常的方式,并且在sendData和close方法中拋出異常:

public class Connection implements AutoCloseable {
  public void sendData() throws Exception {
    throw new Exception("send data");
  }
  @Override
  public void close() throws Exception {
    throw new MyException("close");
  }
}

修改main方法:

public class TryWithResource {
  public static void main(String[] args) {
    try {
      test();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
  private static void test() throws Exception {
    Connection conn = null;
    try {
      conn = new Connection();
      conn.sendData();
    }
    finally {
      if (conn != null) {
        conn.close();
      }
    }
  }
}

運行之后我們發現:

basic.exception.MyException: close
at basic.exception.Connection.close(Connection.java:10)
at basic.exception.TryWithResource.test(TryWithResource.java:82)
at basic.exception.TryWithResource.main(TryWithResource.java:7)
......

好的,問題來了,由于我們一次只能拋出一個異常,所以在最上層看到的是最后一個拋出的異常——也就是close方法拋出的MyException,而sendData拋出的Exception被忽略了。這就是所謂的異常屏蔽。由于異常信息的丟失,異常屏蔽可能會導致某些bug變得極其難以發現,程序員們不得不加班加點地找bug,如此毒瘤,怎能不除!幸好,為了解決這個問題,從Java 1.7開始,大佬們為Throwable類新增了addSuppressed方法,支持將一個異常附加到另一個異常身上,從而避免異常屏蔽。那么被屏蔽的異常信息會通過怎樣的格式輸出呢?我們再運行一遍剛才用try-with-resource包裹的main方法:

java.lang.Exception: send data
	at basic.exception.Connection.sendData(Connection.java:5)
	at basic.exception.TryWithResource.main(TryWithResource.java:14)
	......
	Suppressed: basic.exception.MyException: close
		at basic.exception.Connection.close(Connection.java:10)
		at basic.exception.TryWithResource.main(TryWithResource.java:15)
		... 5 more

可以看到,異常信息中多了一個Suppressed的提示,告訴我們這個異常其實由兩個異常組成,MyException是被Suppressed的異常。可喜可賀!

一個小問題

在使用try-with-resource的過程中,一定需要了解資源的close方法內部的實現邏輯。否則還是可能會導致資源泄露。

舉個例子,在Java BIO中采用了大量的裝飾器模式。當調用裝飾器的close方法時,本質上是調用了裝飾器內部包裹的流的close方法。比如:

public class TryWithResource {
  public static void main(String[] args) {
    try (FileInputStream fin = new FileInputStream(new File("input.txt"));
        GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File("out.txt")))) {
      byte[] buffer = new byte[4096];
      int read;
      while ((read = fin.read(buffer)) != -1) {
        out.write(buffer, 0, read);
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

在上述代碼中,我們從FileInputStream中讀取字節,并且寫入到GZIPOutputStream中。GZIPOutputStream實際上是FileOutputStream的裝飾器。由于try-with-resource的特性,實際編譯之后的代碼會在后面帶上finally代碼塊,并且在里面調用fin.close()方法和out.close()方法。我們再來看GZIPOutputStream類的close方法:

public void close() throws IOException {
  if (!closed) {
    finish();
    if (usesDefaultDeflater)
      def.end();
    out.close();
    closed = true;
  }
}

我們可以看到,out變量實際上代表的是被裝飾的FileOutputStream類。在調用out變量的close方法之前,GZIPOutputStream還做了finish操作,該操作還會繼續往FileOutputStream中寫壓縮信息,此時如果出現異常,則會out.close()方法被略過,然而這個才是最底層的資源關閉方法。正確的做法是應該在try-with-resource中單獨聲明最底層的資源,保證對應的close方法一定能夠被調用。在剛才的例子中,我們需要單獨聲明每個FileInputStream以及FileOutputStream:

public class TryWithResource {
  public static void main(String[] args) {
    try (FileInputStream fin = new FileInputStream(new File("input.txt"));
        FileOutputStream fout = new FileOutputStream(new File("out.txt"));
        GZIPOutputStream out = new GZIPOutputStream(fout)) {
      byte[] buffer = new byte[4096];
      int read;
      while ((read = fin.read(buffer)) != -1) {
        out.write(buffer, 0, read);
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

看完上述內容,你們掌握如何在Java中使用try-with-resource語句的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注創新互聯網站建設公司行業資訊頻道,感謝各位的閱讀!

另外有需要云服務器可以了解下創新互聯建站newbst.com,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。

本文標題:如何在Java中使用try-with-resource語句-創新互聯
地址分享:http://newbst.com/article44/dipshe.html

成都網站建設公司_創新互聯,為您提供Google自適應網站小程序開發標簽優化網站改版網站設計

廣告

聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯

網站建設網站維護公司