【发布时间】:2016-03-02 10:59:16
【问题描述】:
我正在创建一个 java 程序,它采用父路径并删除给定路径中的所有文件和文件夹。我可以删除父文件夹中另一个文件夹中的文件和文件夹的文件,但无法删除第 3 级的文件夹。
这是我的代码:
package com.sid.trial;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
public class DeleteFilesOfDirectoryWithFilters {
public static void main(String[] args) {
String parentPath = "D:\\tester";
List<String> folderPaths = deleteFiles(parentPath);
deleteFolders(folderPaths);
}
public static void deleteFolders(List<String> folderPaths) {
for(String path : folderPaths){
File folder = new File(path);
if(folder.delete())
System.out.println("Folder "+folder.getName()+" Successfully Deleted.");
}
}
public static List<String> deleteFiles(String path){
File folder = new File(path);
File[] files = folder.listFiles();
List<String> folderPaths = new ArrayList<String>();
String folderPath = path;
if(files.length == 0){
System.out.println("Directory is Empty or No FIles Available to Delete.");
}
for (File file : files) {
if (file.isFile() && file.exists()) {
file.delete();
System.out.println("File "+file.getName()+" Successfully Deleted.");
} else {
if(file.isDirectory()){
folderPath = file.getAbsolutePath();
char lastCharacter = path.charAt(path.length()-1);
if(!(lastCharacter == '/' || lastCharacter == '\\')){
folderPath = folderPath.concat("\\");
}
/*folderPath = folderPath.concat(file.getName());*/
System.out.println(folderPath);
folderPaths.add(folderPath);
}
}
}
for(String directoryPath : folderPaths){
List<String> processedFiles = new ArrayList<String>();
processedFiles = deleteFiles(directoryPath);
folderPaths.addAll(processedFiles);
}
return folderPaths;
}
}
【问题讨论】:
-
这是一个练习吗?否则你可以看看 commons-io - FileUtils.cleanDirectory: commons.apache.org/proper/commons-io/apidocs/src-html/org/…
-
@Siddharth 看看下面我的解决方案。
-
请不要要求读者为您做所有事情 - Stack Overflow 不是免费的编码服务。关键是人们愿意帮助您实现目标,因此愿意接受人们的想法和建议,并将其修改为您的用例。