我想写一个删除所有空文件夹的函数,可以选择忽略某些文件类型(允许的文件类型存储在hashmap中),并告诉它是否应该查看目录。
调用
HashMap<String, Boolean> allowedFileTypes = new HashMap<String, Boolean>();
allowedFileTypes.put("pdf", true);
deleteEmptyFolders("ABSOLUTE PATH", allowedFileTypes, true);
功能:
public static void deleteEmptyFolders(String folderPath, HashMap<String, Boolean> allowedFileTypes, boolean followDirectory) {
File targetFolder = new File(folderPath);
File[] allFiles = targetFolder.listFiles();
if (allFiles.length == 0)
targetFolder.delete();
else {
boolean importantFiles = false;
for (File file : allFiles) {
String fileType = "folder";
if (!file.isDirectory())
fileType = file.getName().substring(file.getName().lastIndexOf('.') + 1);
if (!importantFiles)
importantFiles = (allowedFileTypes.get(fileType) != null);
if (file.isDirectory() && followDirectory)
deleteEmptyFolders(file.getAbsolutePath(), allowedFileTypes, followDirectory);
}
// if there are no important files in the target folder
if (!importantFiles)
targetFolder.delete();
}
}
问题是没有任何事情发生,即使它查看所有文件夹直到结束。这是一个好方法还是我完全错过了什么?
答案 0 :(得分:2)
这段代码以递归方式删除所有空文件夹或目录:
public class DeleteEmptyDir {
private static final String FOLDER_LOCATION = "E:\\TEST";
private static boolean isFinished = false;
public static void main(String[] args) {
do {
isFinished = true;
replaceText(FOLDER_LOCATION);
} while (!isFinished);
}
private static void replaceText(String fileLocation) {
File folder = new File(fileLocation);
File[] listofFiles = folder.listFiles();
if (listofFiles.length == 0) {
System.out.println("Folder Name :: " + folder.getAbsolutePath() + " is deleted.");
folder.delete();
isFinished = false;
} else {
for (int j = 0; j < listofFiles.length; j++) {
File file = listofFiles[j];
if (file.isDirectory()) {
replaceText(file.getAbsolutePath());
}
}
}
}
}
答案 1 :(得分:0)
您可以使用代码删除使用Java的空文件夹。
public static long deleteFolder(String dir) {
File f = new File(dir);
String listFiles[] = f.list();
long totalSize = 0;
for (String file : listFiles) {
File folder = new File(dir + "/" + file);
if (folder.isDirectory()) {
totalSize += deleteFolder(folder.getAbsolutePath());
} else {
totalSize += folder.length();
}
}
if (totalSize ==0) {
f.delete();
}
return totalSize;
}
答案 2 :(得分:0)
我能想到的最短代码是遵循 Java >=8 代码:
Files.walk(Paths.get("/my/base/dir/"))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.filter(File::isDirectory)
.forEach(File::delete);
使用您需要包含/排除某些文件夹的任何子句添加第二个(或更多)过滤器语句。 File::delete 不应删除包含内容的文件夹。 使用风险自负。