<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Java 7 中的`try-with-resources` > 原文: [https://howtodoinjava.com/java7/try-with-resources/](https://howtodoinjava.com/java7/try-with-resources/) [**Java 7**](//howtodoinjava.com/category/java-7/ "java 7 features") 為懶惰的 Java 開發人員帶來了一些非常好的特性。`try-with-resource`是這樣的特性之一,它可以減少代碼行,并使代碼更健壯。 在本教程中,我將討論有關此特性的內容。 ![java 7 features](https://img.kancloud.cn/f9/81/f981c69f6997d396c90a7f924bdbb181_478x405.png "java 7 features") ```java Sections in this post: The old way of resource cleanup (Before java 7) The new fancy way with try-with-resources (syntax example) How actually it works? Adding functionality to custom resources Final notes ``` ## 資源清除的舊方法(在 Java 7 之前) 我們長期以來一直在這樣做。 例如從文件系統讀取文件。 代碼可能看起來有所不同,但流程如下例所示: ```java public class ResourceManagementBeforeJava7 { public static void main(String[] args) { BufferedReader br = null; try { String sCurrentLine; br = new BufferedReader(new FileReader("C:/temp/test.txt")); while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } ``` 這些類型的代碼在具有大量 IO 操作的應用程序代碼庫中非常常見。 `try`和`catch`塊中的代碼本質上很重要,并且具有一些特定于應用程序的邏輯。 但是,`finally`塊呢? 在大多??數情況下,最后只是復制粘貼了`finally`塊,目的是通過關閉它們來避免損壞資源。 當您有 3-4 個這樣的資源要在單個`finally`塊中關閉時,這些`finally`塊看起來更難看。 當我們知道時,您是否認為這些`finally`塊不必要地存在,我們必須以任何方式關閉資源而沒有任何異常情況? Java 7 通過`try-with-resources`特性解決了這個問題。 ## 使用`try-with-resources`的新方法(語法示例) 現在看看在 Java 7 中打開和關閉資源的新方法。 ```java public class ResourceManagementInJava7 { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("C:/temp/test.txt"))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } } } ``` 有兩件事需要密切注意: 1. 文件資源(`BufferedReader`)以特殊方式在`try`塊中打開(在小括號內)。 2. `finally`塊完全消失了。 最后但并非最不重要的一點是,代碼看起來很漂亮且易于閱讀。 很好,對嗎? 但是實際上是如何工作的? ## 實際上如何運作? 在 Java 7 中,我們有一個新的超接口[**`java.lang.AutoCloseable`**](https://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html "AutoCloseable")。 此接口有一種方法: ```java void close() throws Exception; ``` Java 文檔建議將此接口**實現在不再需要它時必須關閉的任何資源上**。 當我們在特殊的`try-with-resource`塊中打開任何此類`AutoCloseable`資源時,在`try`塊完成后, **JVM 會對在`try()`塊**中初始化的所有資源調用此`close()`方法。 例如,`BufferedReader`已實現`close()`方法文件如下: ```java public void close() throws IOException { synchronized (lock) { if (in == null) return; in.close(); in = null; cb = null; } } ``` 由于上述方法定義,當 JVM 調用此方法時,所有基礎流或 IO 資源都將關閉。 ## 向自定義資源添加功能 好吧,這是一個很好的資源清理設計。 但是它僅適用于 JDK 本機類嗎? 沒有。 您也可以將其用于自定義資源。 例如,我在以下代碼中創建了一個自定義資源: ```java public class CustomResource implements AutoCloseable { public void accessResource() { System.out.println("Accessing the resource"); } @Override public void close() throws Exception { System.out.println("CustomResource closed automatically"); } } ``` 現在,我將在示例代碼中使用它: ```java public class TryWithCustomResource { public static void main(String[] args) { try(CustomResource cr = new CustomResource()) { cr.accessResource(); } catch (Exception e) { e.printStackTrace(); } } } Putput in console: Accessing the resource CustomResource closed automatically ``` 控制臺中的輸出清楚地證明,`try`塊完成后,資源將自動關閉。 ## 最后注意事項 這就是 Java 7 中使用`try-with-resources`進行自動資源管理的全部內容。讓我們逐點記下重點: * 在 Java 7 之前,我們必須使用`finally`塊來清理資源。 `finally`塊不是強制性的,但是清理資源是為了防止系統損壞。 * 使用 Java 7,無需顯式的資源清理。 它是自動完成的。 * 在`try-with-resources`塊(`try(…){…}`)中初始化資源時完成自動資源清理。 * 由于新接口`AutoCloseable`而發生清除。 `try`塊完成后,JVM 將立即調用其`close`方法。 * 如果要在自定義資源中使用此特性,則必須實現`AutoCloseable`接口。 否則程序將無法編譯。 * 您不應在代碼中調用`close()`方法。 這應該自動稱為 JVM。 手動調用它可能會導致意外結果。 **祝您學習愉快!**
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看