删除目录的代码,递归子文件夹,没有如果是文件则删除,上线运行过程中一直没有问题,但一次私有化部署时,删除文件夹总是报错,经过排查是因为一些失效的软链接文件删除不掉(手动是可以删除的,权限也验证没问题)
public void delDir(String path) {
try {
Path dirPath = Paths.get(path);
if (Files.exists(dirPath) && Files.isDirectory(dirPath)) {
File dirPathFile = dirPath.toFile();
if (null == dirPathFile) {
return;
}
File[] files = dirPathFile.listFiles();
if (null == files) {
return;
}
for (File file : files) {
if (file.isFile()) {
file.delete();
} else {
delDir(file.getPath());
}
}
Files.delete(dirPath);
}
} catch (Exception e) {
log.error("删除目录失败,path = {}", path, e);
Assert.state(false, "删除目录失败");
}
}
最终发现,if (file.isFile()) 判断失效的软链接文件时,返回了false, 惊讶! 软链接文件就不是文件么? 进入isFile() 代码看,
Tests whether the file denoted by this abstract pathname is a normal file.
normal file是什么? 以后继续了解,看到此文章的,可以评论下,总之先解决问题吧,删除文件夹的代码改成下面的方式,改成先判断是不是文件夹
public void delDir(String path) {
try {
Path dirPath = Paths.get(path);
if (Files.exists(dirPath) && Files.isDirectory(dirPath)) {
File dirPathFile = dirPath.toFile();
if (null == dirPathFile) {
return;
}
File[] files = dirPathFile.listFiles();
if (null == files) {
return;
}
for (File file : files) {
if(file.isDirectory()){ //先判断是不是文件夹
delDir(file.getPath());
}
else{ //这样就覆盖到了删除失效的软链接情况
file.delete();
}
}
Files.delete(dirPath);
}
} catch (Exception e) {
log.error("删除目录失败,path = {}", path, e);
Assert.state(false, "删除目录失败");
}
}