java 删除非空文件夹
程序员文章站
2022-05-15 08:49:34
...
java 中如何删除非空的目录呢?
使用递归,代码如下:
/***
* delete a directory/folder
*
* @param someFile
*/
public static boolean deleteDir(File someFile) {
if (!someFile.exists()) {
System.out.println("[deleteDir]File " + someFile.getAbsolutePath()
+ " does not exist.");
return false;
}
if (someFile.isDirectory()) {// is a folder
File[] files = someFile.listFiles();
for (File subFile : files) {
boolean isSuccess = deleteDir(subFile);
if (!isSuccess) {
return isSuccess;
}
}
} else {// is a regular file
boolean isSuccess = someFile.delete();
if (!isSuccess) {
return isSuccess;
}
}
if (someFile.isDirectory()) {
return someFile.delete();
} else {
return true;
}
}
说明:若删除成功,则返回true,否则返回false
上一篇: docker compose
下一篇: Java小练习 数字翻转
推荐阅读