版权声明:欢迎评论和转载,转载请注明来源。 https://blog.csdn.net/zy332719794/article/details/80164205
Java的库中没有提供直接的删除文件夹及其子文件的方法,需要自己写,下面提供两种删除方式。
/*** 删除文件夹及其子文件(栈方式)**/
public static boolean deleteDirectory(File dir) {Stack<File> stackFiles = new Stack<File>();stackFiles.push(dir);while (stackFiles.size() > 0) {File currentFile = stackFiles.peek();File[] subFiles = currentFile.listFiles(); for (int i = 0; i < subFiles.length; i++) {if (subFiles[i].isFile()) {if (!subFiles[i].delete()) {return false;}} else {stackFiles.push(subFiles[i]);}}if (currentFile == stackFiles.peek()) {if (!currentFile.delete()) {return false;}stackFiles.pop();}}return true;
}
/*** 删除文件夹及其子文件(递归方式)**/
public static boolean deleteDirectory(File dir) {if (dir.isDirectory()) {File[] subFiles = dir.listFiles();for (int i = 0; i < subFiles.length; i++) {boolean success = deleteDirectory(subFiles[i]);if (!success) {return false;}}}return dir.delete();
}