Recursive deletion causing a stack overflow error

泄露秘密 提交于 2019-12-24 10:48:41

问题


I asked a question about how to delete all files from folders in a directory but keep the folders, this can be found here:

How to delete files of a directory but not the folders

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();
    }
}

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?


回答1:


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();
}

or with 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;
    }
})



回答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();
    }
}



回答3:


 File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");

You are creating the same file again and again. Declare that file outside the function.

Your recursion is different from the suggested one.

public void DeleteFiles( File file) {
    System.out.println("Called deleteFiles");
    if (file.isDirectory()) {
        for (File f : file.listFiles()) {
            DeleteFiles(f);
        }
    } else {
        file.delete();
    }
}


来源:https://stackoverflow.com/questions/15042432/recursive-deletion-causing-a-stack-overflow-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!