LoginSignup
2
2

More than 3 years have passed since last update.

【Java7以降】一時ファイル削除漏れを防ぐ

Last updated at Posted at 2020-09-29

目的

一時ファイルの削除し忘れや、異常終了時にファイル削除されずに終了してしまうことを防ぐ。

実装例

delete文を使用してファイル削除

delete文で一時ファイル削除
    Path path = null;
    try {
        // 一時ファイル作成
        path = Files.createTempFile("test", ".tmp");
        OutputStream out = Files.newOutputStream(path);
        String data = "test";
        out.write(data.getBytes());

        // ファイルに書き込み
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 処理終了時にファイル削除
        Files.deleteIfExists(path);
    }

この実装では、JVM異常終了時には削除されないこともあるようです。

DELETE_ON_CLOSEを使用してファイル削除

DELETE_ON_CLOSEを使用した一時ファイル削除
    Path path = null;
    try {
        // 一時ファイル作成
        path = Files.createTempFile("test", ".temp");
        try (BufferedWriter bw = Files.newBufferedWriter(path, StandardOpenOption.DELETE_ON_CLOSE)) {
            String data = "test";
            // ファイルに書き込み
            bw.write(data);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

StandardOpenOptionのDELETE_ON_CLOSEは、ファイルのオープン時のオプションとして利用すると
ストリームをクローズした時に自動的にファイルが削除される。
さらに「try-with-resources」構文を使用することで、close処理を実装しなくても自動的にクローズとファイル削除が実行されるので、実装もすっきりして削除漏れもなくなります。

2
2
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
2
2