How to delete a folder with files using Java

2019-01-07 08:10发布

I want to create and delete a directory using Java, but it isn't working.

File index = new File("/home/Work/Indexer1");
if (!index.exists()) {
    index.mkdir();
} else {
    index.delete();
    if (!index.exists()) {
        index.mkdir();
    }
}

24条回答
放荡不羁爱自由
2楼-- · 2019-01-07 08:18

You can make recursive call if sub directories exists

import java.io.File;

class DeleteDir {
public static void main(String args[]) {
deleteDirectory(new File(args[0]));
}

static public boolean deleteDirectory(File path) {
if( path.exists() ) {
  File[] files = path.listFiles();
  for(int i=0; i<files.length; i++) {
     if(files[i].isDirectory()) {
       deleteDirectory(files[i]);
     }
     else {
       files[i].delete();
     }
  }
}
return( path.delete() );
}
}
查看更多
Animai°情兽
3楼-- · 2019-01-07 08:19

we can use the spring-core dependency;

boolean result = FileSystemUtils.deleteRecursively(file);
查看更多
Summer. ? 凉城
4楼-- · 2019-01-07 08:21

Just a one-liner.

import org.apache.commons.io.FileUtils;

FileUtils.deleteDirectory(new File(destination));

Documentation here

查看更多
Deceive 欺骗
5楼-- · 2019-01-07 08:22

Guava 21+ to the rescue. Use only if there are no symlinks pointing out of the directory to delete.

com.google.common.io.MoreFiles.deleteRecursively(
      file.toPath(),
      RecursiveDeleteOption.ALLOW_INSECURE
) ;

(This question is well-indexed by Google, so other people usig Guava might be happy to find this answer, even if it is redundant with other answers elsewhere.)

查看更多
可以哭但决不认输i
6楼-- · 2019-01-07 08:23

My basic recursive version, working with older versions of JDK:

public static void deleteFile(File element) {
    if (element.isDirectory()) {
        for (File sub : element.listFiles()) {
            deleteFile(sub);
        }
    }
    element.delete();
}
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-07 08:25

I prefer this solution on java 8:

  Files.walk(pathToBeDeleted)
    .sorted(Comparator.reverseOrder())
    .map(Path::toFile)
    .forEach(File::delete);

From this site: http://www.baeldung.com/java-delete-directory

查看更多
登录 后发表回答