Java SimpleFileVisitor extend post Visit Directory

Description

Java SimpleFileVisitor extend post Visit Directory

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("dir");
    FileVisitor<Path> visitor = new DeleteDirVisitor();
    try {//from www  . j  a  v  a 2 s . c  om
      Files.walkFileTree(dirToDelete, visitor);
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}
class DeleteDirVisitor extends SimpleFileVisitor<Path> {
  @Override
  public FileVisitResult postVisitDirectory(Path dir, IOException e)
      throws IOException {
    FileVisitResult result = FileVisitResult.CONTINUE;

    // delete the directory at the end
    if (e != null) {
      System.out.format("Error deleting %s. %s%n", dir, e.getMessage());
      result = FileVisitResult.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 FileVisitResult.CONTINUE;
  }
}



PreviousNext

Related