Java – Try with Resources


1.介紹

Java 7中引入的對try-with-resources的支持使我們能夠聲明將在try塊中使用的資源,並確保在執行該塊后將關閉資源。

⚠️:聲明的資源必須實現AutoCloseable接口。


2.使用try-with-resources

簡單地說,要自動關閉,必須在try中聲明和初始化資源,如下所示:

try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
    writer.println("Hello World");
}

3.使用try-with-resources代替try–catch-finally

使用簡單明顯的try-with-resources代替傳統和冗長的try-catch-finally 塊。

讓我們比較以下代碼示例–首先是一個典型的try-catch-finally塊,然后是新方法,使用等效的try-with-resources塊:

Scanner scanner = null;
try {
    scanner = new Scanner(new File("test.txt"));
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (scanner != null) {
        scanner.close();
    }
}

這是使用try-with-resources的超級簡潔解決方案:

try (Scanner scanner = new Scanner(new File("test.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
}

你最鍾意那種呢?


4.具有多個資源的try-with-resources

通過用分號分隔多個資源,可以在try-with-resources塊中聲明多個資源:

try (Scanner scanner = new Scanner(new File("testRead.txt"));
    PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
    while (scanner.hasNext()) {
    writer.print(scanner.nextLine());
    }
}

5.自定義實現AutoCloseable接口的資源

要構造一個將由try-with-resources塊正確處理的自定義資源,該類應需要實現Closeable或AutoCloseable接口,並覆蓋close方法:

public class MyResource implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("Closed MyResource");
    }
}

6.資源關閉順序

資源首先將會被定義(創建),然后使用,最后被關閉。讓我們看一下示例:

資源1:

public class AutoCloseableResourcesFirst implements AutoCloseable {
 
    public AutoCloseableResourcesFirst() {
        System.out.println("Constructor -> AutoCloseableResources_First");
    }
 
    public void doSomething() {
        System.out.println("Something -> AutoCloseableResources_First");
    }
 
    @Override
    public void close() throws Exception {
        System.out.println("Closed AutoCloseableResources_First");
    }
}

資源2:

public class AutoCloseableResourcesSecond implements AutoCloseable {
 
    public AutoCloseableResourcesSecond() {
        System.out.println("Constructor -> AutoCloseableResources_Second");
    }
 
    public void doSomething() {
        System.out.println("Something -> AutoCloseableResources_Second");
    }
 
    @Override
    public void close() throws Exception {
        System.out.println("Closed AutoCloseableResources_Second");
    }
}

使用資源:

private void orderOfClosingResources() throws Exception {
    try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst();
        AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {
 
        af.doSomething();
        as.doSomething();
    }
}

輸出:

Constructor -> AutoCloseableResources_First
Constructor -> AutoCloseableResources_Second
Something -> AutoCloseableResources_First
Something -> AutoCloseableResources_Second
Closed AutoCloseableResources_Second
Closed AutoCloseableResources_First


7.catch&finally

一個帶有資源的try塊仍然可以包含catch和finally塊,其工作方式與傳統try塊相同。

8.總結

在本文中,我們討論了如何使用try-with-resources,如何用try-with-resources替換try,catch和finally,如何使用AutoCloseable構建自定義資源以及了解關閉資源的順序。


關注筆者公眾號,推送各類原創/優質技術文章 ⬇️


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM