java递归删除文件夹
Earlier we learned how to create a file in java and how to delete a file in java. Here we will learn how to delete a non-empty directory/folder in java recursively.
之前我们学习了如何在java中创建文件以及如何 在java 中删除文件 。 在这里,我们将学习如何递归删除Java中的非空目录/文件夹。
Java删除目录 (Java Delete Directory)
Java File delete()
method deletes a file or an empty directory. However, if directory is not empty, it doesn’t delete it and returns false.
Java File delete()
方法删除文件或空目录。 但是,如果目录不为空,则不会将其删除并返回false。
We will use delete() function recursively to delete a directory/folder in java program.
我们将递归使用delete()函数来删除Java程序中的目录/文件夹。
package com.journaldev.files;
import java.io.File;
/**
* This utility class can be used to delete
* folders recursively in java
* @author pankaj
*/
public class DeleteFolderRecursively {
public static void main(String[] args) {
String folder = "/Users/pankaj/tmp";
//delete folder recursively
recursiveDelete(new File(folder));
}
public static void recursiveDelete(File file) {
//to end the recursive loop
if (!file.exists())
return;
//if directory, go inside and call recursively
if (file.isDirectory()) {
for (File f : file.listFiles()) {
//call recursively
recursiveDelete(f);
}
}
//call delete to delete files and empty directory
file.delete();
System.out.println("Deleted file/folder: "+file.getAbsolutePath());
}
}
Here we are using delete() to delete the folder contents and if it’s directory, we are recursively calling recursiveDelete
method.
在这里,我们使用delete()删除文件夹内容,如果它是目录,我们将递归调用recursiveDelete
方法。
Here is the output of the above program which deletes the directory.
这是上述程序删除目录的输出。
Deleted file/folder: /Users/pankaj/tmp/.DS_Store
Deleted file/folder: /Users/pankaj/tmp/data/data.dat
Deleted file/folder: /Users/pankaj/tmp/data/data.sql
Deleted file/folder: /Users/pankaj/tmp/data
Deleted file/folder: /Users/pankaj/tmp/DB.xml
Deleted file/folder: /Users/pankaj/tmp/item.xsd
Deleted file/folder: /Users/pankaj/tmp/ms/data.txt
Deleted file/folder: /Users/pankaj/tmp/ms/project.doc
Deleted file/folder: /Users/pankaj/tmp/ms
Deleted file/folder: /Users/pankaj/tmp
You can use this utility method to delete a non-empty directory.
您可以使用此实用程序方法删除非空目录。
翻译自: https://www.journaldev.com/833/java-delete-directory-folder
java递归删除文件夹