LoginSignup
5
10

More than 5 years have passed since last update.

ディレクトリ削除処理(再帰処理)

Posted at

Javaの処理で対象ディレクトリの配下のファイルを含め、削除をする処理。
※JavaのFileクラスのdeleteメソッドでは
 ディレクトリ配下にファイルがある場合はエラーとなるため、
 再帰的な処理が必要となる。
 ApacheCommonsにはフォルダごと削除するメソッドもある。

/**
 * 対象パスのディレクトリの削除を行う.<BR>
 * ディレクトリ配下のファイル等が存在する場合は<BR>
 * 配下のファイルをすべて削除します.
 *
 * @param dirPath 削除対象ディレクトリパス
 * @throws Exception
 */
public static void deleteDirectory(final String dirPath) throws Exception {
    File file = new File(dirPath);
    recursiveDeleteFile(file);
}

/**
 * 対象のファイルオブジェクトの削除を行う.<BR>
 * ディレクトリの場合は再帰処理を行い、削除する。
 *
 * @param file ファイルオブジェクト
 * @throws Exception
 */
private static void recursiveDeleteFile(final File file) throws Exception {
    // 存在しない場合は処理終了
    if (!file.exists()) {
        return;
    }
    // 対象がディレクトリの場合は再帰処理
    if (file.isDirectory()) {
        for (File child : file.listFiles()) {
            recursiveDeleteFile(child);
        }
    }
    // 対象がファイルもしくは配下が空のディレクトリの場合は削除する
    file.delete();
}
5
10
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
5
10