@okasigenn (松本 博己)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Javaでのファイル、ディレクトリ削除について質問です。

Q&A

Javaでファイル、ディレクトリ削除をしたいです。
環境はEclipsです。
下記コードで引数の指定パスのディレクトリのファイルを削除→ディレクトリを削除を行いたいのですが、実行結果はファイルのみ削除完了、ディレクトリは削除できずとなってしまいます。
どなたか教えていただけると幸いです。

import java.io.File;
public class DirUtil {

/**
 * 指定パスのディレクトリを削除します。<br/>
 * ディレクトリの中に存在するファイルまたはディレクトリすべて削除します。<br/>
 * 指定パスがディレクトリでない、または存在しない場合、例外 IllegalArgumentException をスローします。
 *
 * @param dir 削除対象ディレクトリパス
 * @throws IllegalArgumentException 指定パスがディレクトリでない、または存在しない場合
 */
public static void remove(File dir) {




    try {
        //引数のパスのディレクトリが存在しない、かつがパスのファイルがディレクトリではない場合
        if(!dir.exists() || !dir.isDirectory()) {
            throw new IllegalArgumentException("ディレクトリが存在しないまたはディレクトリではありません");
            }else {
            //ファイルをリストに入れる
            File[] fileList = dir.listFiles();
            //for文で1つずつ取り出し削除する
            for(int i =0;i<fileList.length-1; i++) {

// fileList[i].delete();
File filePath = new File(dir + File.separator + fileList[i]);
if(filePath.isDirectory() == true){
// filePath.delete();
remove(filePath);
}
if(filePath.isFile() == true) {
filePath.delete();
}
// else {
// fileList[i].delete();
// }
}

    }
        dir.delete();
    }
    catch(NullPointerException e) {
        throw new IllegalArgumentException("引数にnullが指定されています");
    }


    catch(Exception e) {
        throw new IllegalArgumentException("エラーです");
    }

}
0 likes

1Answer

どのようなエラーが発生していますか。
例外が発生している場合、そのスタックトレースを貼ったほうが良いと思います。

0Like

Comments

  1. @okasigenn

    Questioner

    DirUtil.remove(dir);
    assertFalse(dir.exists());

    テストでこのコードの際に失敗してしまいます。
    ディレクトリが残っている際に失敗になるケースです。
  2. for(int i =0;i<fileList.length-1; i++) {

    for(int i =0;i<fileList.length; i++) {
    ですかね?

Your answer might help someone💌