gpt4 book ai didi

java - 在java中清除没有排除文件的目录

转载 作者:行者123 更新时间:2023-12-02 13:09:03 24 4
gpt4 key购买 nike

我尝试删除目录中没有文件路径在我的数组中的文件

    public static boolean deleteDir(File dir, List<String> exclusionList) throws IOException {
if (exclusionList != null && exclusionList.contains(dir.getCanonicalPath())) { // skip file

System.out.println("Skipped: " + dir.getCanonicalPath());
return true;
}

System.out.println("Deleting: " + dir.getCanonicalPath());
if (dir.isDirectory()) {
File[] children = dir.listFiles();
boolean success = true;
for (File element : children) {
if (!deleteDir(element, exclusionList)) {
success = false;
}
}
return success;
}

return dir.delete();
}

这是我的删除功能,可以很好地删除 .txt .yml 等文件,但是当它必须删除文件夹(文件夹内容删除完美)但文件夹存在时,我有很多空文件夹;/

最佳答案

该问题是由目录的处理方式引起的:

System.out.println("Deleting: " + dir.getCanonicalPath());
if (dir.isDirectory()) {
File[] children = dir.listFiles();
boolean success = true;
for (File element : children) {
if (!deleteDir(element, exclusionList)) {
success = false;
}
}
return success; // <= for directories the method returns here
}

return dir.delete();

在目录中,该方法将为所有子元素递归调用deleteDir,并检查所有子元素是否已成功删除。之后该方法只是返回,而不删除目录本身。一个简单的解决方法是仅在删除某个子元素失败时才终止:

System.out.println("Deleting: " + dir.getCanonicalPath());
if (dir.isDirectory()) {
File[] children = dir.listFiles();
boolean success = true;
for (File element : children) {
if (!deleteDir(element, exclusionList)) {
success = false;
}
}

// return only if some child couldn't be deleted.
if(!success)
return false;
}

// delete the directory itself (or the file, if a file is passed as parameter)
return dir.delete();

关于java - 在java中清除没有排除文件的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44036083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com