user2065929
user2065929

Reputation: 1095

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:

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?

Upvotes: 1

Views: 509

Answers (3)

Ryan Stewart
Ryan Stewart

Reputation: 128919

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

Upvotes: 4

Arpit
Arpit

Reputation: 12797

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

Upvotes: 2

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29233

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

Upvotes: 2

Related Questions