直接调用File
类的delete()
方法,在流未关闭、存在子目录和文件的情况下,删除会失败,那么我们需要递归全部子项,一一删除:
public static boolean deleteFileOrDir(String filePath) {
try {
File file = new File(filePath);
if (file.isDirectory()) {
return deleteDir(file);
}
//是文件
if (file.exists()) {
return file.delete();
}
return true;
} catch (Exception e) {
log.error("deleteFileOrDir error, filePath:{}, ex:{}", filePath, e.getMessage(), e);
return false;
}
}
private static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (String child : children) {
boolean success = deleteDir(new File(dir, child));
if (!success) {
return false;
}
}
}
return dir.delete();
}