LoginSignup
0
0

More than 3 years have passed since last update.

try-with-resourseが便利

Posted at

リソースを自動で閉じる

ファイル開いて、try-catchして、閉じるみたいな
よくやると思うんですけれど
finallyとか使おうとすると

長い.java
    // try
        // ファイルを開く

    // catch
        // 例外処理

    // finally
        // ファイルを閉じる

    public static void main(String[] args) {

        String filePath = "C:\\Windows\\System32";
        BufferedReader bufferedReader = null;

        try {
            // ファイルを開く
            File file = new File(filePath);

            // 読み込み
            FileReader fileReader = new FileReader(file);
            bufferedReader = new BufferedReader(fileReader);

            // 出力
            String data;
            while ((data = bufferedReader.readLine()) != null) {
                System.out.println(data);
            }

        } catch (IOException e) {
            System.out.println("ひらけん");

        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    System.out.println("とじれん");
                }
            }
        }
    }

これを、try-with-resource文を使うと...

すまーと.java
    // try
        // ファイルを開く、勝手に閉じる

    // catch
        // 例外処理

    public static void main(String[] args) {

        String filePath = "C:\\Windows\\System32";

        try (FileReader fileReader = new FileReader(new File(filePath));
                BufferedReader bufferedReader = new BufferedReader(fileReader);) {

            // 出力
            String data;
            while ((data = bufferedReader.readLine()) != null) {
                System.out.println(data);
            }

        } catch (IOException e) {
            System.out.println("ひらけん");
        }
    }

tryの次の括弧()内部で宣言した変数は
勝手に閉じられる対象となります(java.lang.AutoCloseable)

try句の中までのスコープで、まぁtry句の中で宣言するのと使い勝手は変わりません

勝手に閉じてくれるとか気が利きすぎてて便利すぎでは

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0