我问了一个关于如何从目录中的文件夹中删除所有文件但保留文件夹的问题,可以在这里找到:
How to delete files of a directory but not the folders
其中一个目的是使用递归来实现这个目标:
public void DeleteFiles() {
File file =
new File(
"D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/"+
"resources/pdf/");
System.out.println("Called deleteFiles");
if (file.isDirectory()) {
for (File f : file.listFiles()) {
DeleteFiles();
}
} else {
file.delete();
}
}
然而,我只是得到一个充满了Called deleteFiles的控制台,直到我得到堆栈溢出错误,它似乎没有通过目录查找文件并删除它们,我怎么能实现这个?
答案 0 :(得分:4)
当有更简单的解决方案时,递归会遇到麻烦。使用commons-io:
import java.io.File;
import org.apache.commons.io.FileUtils;
import static org.apache.commons.io.filefilter.TrueFileFilter.TRUE;
File root = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
Iterator<File> files = FileUtils.iterateFiles(root, TRUE, TRUE);
for (File file : files) {
file.delete();
}
或JDK 7:
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
Path root = Paths.get("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
file.delete();
return FileVisitResult.CONTINUE;
}
})
答案 1 :(得分:2)
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
您正在反复创建同一个文件。在函数外声明该文件。
您的递归与建议的递归不同。
public void DeleteFiles( File file) {
System.out.println("Called deleteFiles");
if (file.isDirectory()) {
for (File f : file.listFiles()) {
DeleteFiles(f);
}
} else {
file.delete();
}
}
答案 2 :(得分:2)
public void DeleteFiles() {
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
System.out.println("Called deleteFiles");
DeleteFiles(file);
}
public void DeleteFiles(File file) {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
DeleteFiles(f);
}
} else {
file.delete();
}
}