onsen code monkey

個人的な日記とプログラミング備忘録です

【Java】try-with-resourcesを使ってファイルの読み書き

try-with-resourcesを使えばいちいちCloseやDisposeしなくてもリソースを自動で解放してくれる

C#のusing的なやつ

条件
・JavaSE7以降
・クラスがAutoCloseableインターフェースおよびCloseableインターフェースを実装していること

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TryWithResources {
    public static void main(String[] args) {

        String inFilePath = "D:\\A.txt";
        String outFilePath = "D:\\C.txt";

        try (FileInputStream in = new FileInputStream(inFilePath);
                FileOutputStream out = new FileOutputStream(outFilePath);) {
            int c;

            // データをコピーする
            while ((c = in.read()) != -1) {
                out.write(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

参考サイト様
try-with-resources文の基本 - Qiita