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:39
private void deleteFileOrFolder(File file){
    try {
        for (File f : file.listFiles()) {
            f.delete();
            deleteFileOrFolder(f);
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}
查看更多
Emotional °昔
3楼-- · 2019-01-07 08:41

Create directory -

File directory = new File("D:/Java/Example");
boolean isCreated = directory.mkdir();

Delete directory -

Refer this resource for detailed explanation - delete directory.

查看更多
不美不萌又怎样
4楼-- · 2019-01-07 08:42

Most of answers (even recent) referencing JDK classes rely on File.delete() but that is a flawed API as the operation may fail silently.
The java.io.File.delete() method documentation states :

Note that the java.nio.file.Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

As replacement, you should favor Files.delete(Path p) that throws an IOException with a error message.

The actual code could be written such as :

Path index = Paths.get("/home/Work/Indexer1");

if (!Files.exists(index)) {
    index = Files.createDirectories(index);
} else {

    Files.walk(index)
         .sorted(Comparator.reverseOrder())  // as the file tree is traversed depth-first and that deleted dirs have to be empty  
         .forEach(t -> {
             try {
                 Files.delete(t);
             } catch (IOException e) {
                 // LOG the exception and potentially stop the processing

             }
         });
    if (!Files.exists(index)) {
        index = Files.createDirectories(index);
    }
}
查看更多
劫难
5楼-- · 2019-01-07 08:43

In JDK 7 you could use Files.walkFileTree() and Files.deleteIfExists() to delete a tree of files.

In JDK 6 one possible way is to use FileUtils.deleteQuietly from Apache Commons which will remove a file, a directory, or a directory with files and sub-directories.

查看更多
时光不老,我们不散
6楼-- · 2019-01-07 08:43

Using Apache Commons-IO, it is following one-liner:

import org.apache.commons.io.FileUtils;

FileUtils.forceDelete(new File(destination));

This is (slightly) more performant than FileUtils.deleteDirectory.

查看更多
淡お忘
7楼-- · 2019-01-07 08:43

Some of these answers seem unnecessarily long:

if (directory.exists()) {
    for (File file : directory.listFiles()) {
        file.delete();
    }
    directory.delete();
}

Works for sub directories too.

查看更多
登录 后发表回答