3
我想编写一个删除所有空文件夹的函数,并且可以忽略某些文件类型(允许的文件类型存储在散列映射中)并告诉它是否应该查看目录内部。删除Java中的所有空文件夹
呼唤:
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();
}
}
的问题是,什么也没发生,即使它看上去通过,直到最后所有文件夹。这是一个好方法还是我完全错过了一些东西?
任何你使用HashMap而不是HashSet的原因? – aioobe 2014-09-24 13:00:48
@aioobe现在你提到它。不,我会做成一套,因为我只会检查它是否为空。谢谢。 – TomTom 2014-09-24 13:03:50
也许这可以帮助你一点:http://stackoverflow.com/a/20281958/2496309 – 2014-09-24 13:04:30