刪除目錄或文件,如果目錄不爲空的話,則遞歸刪除目錄下的所有內容
/**
* 刪除文件或目錄
* 如果是目錄則遞歸刪除目錄下所有內容
* 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;
}