Java - リソースを試してみる

Java –リソースで試す

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. trycatch-finallytry-with-resourcesに置き換える

新しい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. のカスタムリソース 自動クローズ可能

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

出力:

コンストラクター→AutoCloseableResources_First コンストラクター→AutoCloseableResources_Second 何か→AutoCloseableResources_First 何か→AutoCloseableResources_Second AutoCloseableResources_Secondを閉じました AutoCloseableResources_Firstを閉じました

7. catchfinally

try-with-resourcesブロックcan still have the catch and finally blocks –これは従来のtryブロックと同じように機能します。

8. 結論

この記事では、try-with-resourcesの使用方法、trycatchfinallyをtry-with-resourcesに置き換える方法、AutoCloseableを使用してカスタムリソースを構築する方法について説明しました。 )sおよびリソースが閉じられる順序。

この例の完全なsource codeは、this GitHub projectで利用できます。