Java - Delete File Tree

Introduction

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.

Demo

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

import java.io.IOException;
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  w w  . j  av  a  2s .  c om*/
      Files.walkFileTree(dirToDelete, visitor);
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }

  public static FileVisitor<Path> getFileVisitor() {
    class DeleteDirVisitor extends SimpleFileVisitor<Path> {
      @Override
      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 {
          Files.delete(dir);
          System.out.format("Deleted directory %s%n", dir);
        }
        return result;
      }

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

        // Delete the file that we are visiting
        Files.delete(file);

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

    FileVisitor<Path> visitor = new DeleteDirVisitor();

    return visitor;
  }
}

Result