Java - Delete File Tree


You can implement operations such as copying a directory tree, deleting a non-empty directory, finding a file using the FileVisitor API.

The following code uses the FileVisitor API to delete a directory tree.


import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.TERMINATE;

import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
  public static void main(String[] args) {

    Path dirToDelete = Paths.get("YOUR_DIR_PATH_TO_DELETE");
    FileVisitor<Path> visitor = getFileVisitor();

    try {//  w ww . j  a va  2  s.c  om
      Files.walkFileTree(dirToDelete, visitor);
    } catch (IOException e) {

  public static FileVisitor<Path> getFileVisitor() {
    class DeleteDirVisitor extends SimpleFileVisitor<Path> {
      public FileVisitResult postVisitDirectory(Path dir, IOException e)
          throws IOException {

        FileVisitResult result = CONTINUE;

        // Now, delete the directory at the end
        if (e != null) {
          System.out.format("Error deleting %s. %s%n", dir, e.getMessage());
          result = TERMINATE;
        } else {
          System.out.format("Deleted directory %s%n", dir);
        return result;

      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
          throws IOException {

        // Delete the file that we are visiting

        System.out.format("Deleted file %s%n", file);
        return CONTINUE;

    FileVisitor<Path> visitor = new DeleteDirVisitor();

    return visitor;