在Java中,我想删除包含文件和文件夹的文件夹中的所有内容。
public void startDeleting(String path) {
List<String> filesList = new ArrayList<String>();
List<String> folderList = new ArrayList<String>();
fetchCompleteList(filesList, folderList, path);
for(String filePath : filesList) {
File tempFile = new File(filePath);
tempFile.delete();
}
for(String filePath : folderList) {
File tempFile = new File(filePath);
tempFile.delete();
}
}
private void fetchCompleteList(List<String> filesList,
List<String> folderList, String path) {
File file = new File(path);
File[] listOfFile = file.listFiles();
for(File tempFile : listOfFile) {
if(tempFile.isDirectory()) {
folderList.add(tempFile.getAbsolutePath());
fetchCompleteList(filesList,
folderList, tempFile.getAbsolutePath());
} else {
filesList.add(tempFile.getAbsolutePath());
}
}
}
这段代码不能工作,最好的方法是什么?
发布于 2010-09-23 13:47:56
我有这样的东西:
public static boolean deleteDirectory(File directory) {
if(directory.exists()){
File[] files = directory.listFiles();
if(null!=files){
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
}
return(directory.delete());
}
发布于 2010-09-23 13:48:47
试试这个:
public static boolean deleteDir(File dir)
{
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i=0; i<children.length; i++)
return deleteDir(new File(dir, children[i]));
}
// The directory is now empty or this is a file so delete it
return dir.delete();
}
发布于 2010-09-23 13:50:02
可能是嵌套文件夹有问题。您的代码将按找到文件夹的顺序删除它们,这是自上而下的,这是不起作用的。如果您先反转文件夹列表,它可能会起作用。
但我建议您只使用Commons IO这样的库。
https://stackoverflow.com/questions/3775694
复制相似问题