Deleting a directory using the SimpleFileVisitor class - Java File Path IO

Java examples for File Path IO:File Visitor


Deleting a directory using the SimpleFileVisitor class

Demo Code

import java.nio.file.FileVisitResult;
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) {
    try {/*  w  w  w  .j  ava 2s .  c o m*/
      Files.walkFileTree(Paths.get("/home"), new DeleteDirectory());
    } catch (IOException ex) {


class DeleteDirectory extends SimpleFileVisitor<Path> {
  public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
      throws IOException {
    System.out.println("Deleting " + file.getFileName());
    return FileVisitResult.CONTINUE;

  public FileVisitResult postVisitDirectory(Path directory,
      IOException exception) throws IOException {
    if (exception == null) {
      System.out.println("Deleting " + directory.getFileName());
      return FileVisitResult.CONTINUE;
    } else {
      throw exception;

Related Tutorials