递归删除导致堆栈溢出错误 [英] Recursive deletion causing a stack overflow error
本文介绍了递归删除导致堆栈溢出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我问了一个有关如何从目录中的文件夹删除所有文件但保留文件夹的问题,可以在这里找到:
I asked a question about how to delete all files from folders in a directory but keep the folders, this can be found here:
一种有针对性的解决方案是使用递归来实现:
One of the purposed solutions was to use recursion, to achieve this:
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();
}
}
但是我只是得到一个充满了deleteedFiles的控制台,直到出现堆栈溢出错误,它似乎并没有遍历目录来查找文件并将其删除,该如何实现?
However I just get a console full of Called deleteFiles, until I get the stack overflow error, it does not seem to go through the directory to find files and delete them, how can I achieve this?
推荐答案
当有许多更简单的解决方案时,递归会带来麻烦。使用 commons-io :
Recursion is asking for trouble when there are much simpler solutions. With 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;
}
})
这篇关于递归删除导致堆栈溢出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文