删除目录或文件,如果目录不为空的话,则递归删除目录下的所有内容
/**
* 删除文件或目录
* 如果是目录则递归删除目录下所有内容
* ps: 不支持link类型的目录
*
* @param path 要删除的文件
* @return
* @throws IOException
*/
public static boolean delete(Path path) throws IOException {
if (Files.isDirectory(path)) {
return deleteDirectory(path);
} else if (Files.isRegularFile(path)) {
return deleteFile(path);
}
throw new IOException(String.format("cannot handle path:%s", path.toString()));
}
/**
* 删除文件
*
* @param path
* @return
* @throws IOException
*/
private static boolean deleteFile(Path path) throws IOException {
if (!Files.exists(path)) {
return true;
}
return Files.deleteIfExists(path);
}
/**
* 迭代的清空目录
*
* @return
*/
private static boolean deleteDirectory(Path path) throws IOException {
if (!Files.exists(path)) {
return true;
}
var children = Files.list(path).collect(Collectors.toList());
boolean success = true;
for (Path child : children) {
try {
boolean stepResult;
if (Files.isDirectory(child)) {
stepResult = deleteDirectory(child);
} else {
stepResult = deleteFile(child);
}
if (!stepResult) {
success = false;
}
} catch (IOException e) {
success = false;
}
}
if (success) {
success = Files.deleteIfExists(path);
}
return success;
}