Tuesday, August 02, 2011

Java 7: Deleting a Directory by Walking the File Tree

The Java 7 NIO library allows you to walk a file tree and visit each file in the tree. You do this by implementing a FileVisitor and then calling Files.walkFileTree using the visitor. The visitor has four methods:
  • visitFile: Invoked for a file in a directory.
  • visitFileFailed: Invoked for a file that could not be visited.
  • preVisitDirectory: Invoked for a directory before entries in the directory are visited.
  • postVisitDirectory: Invoked for a directory after entries in the directory, and all of their descendants, have been visited.

Recursively Delete all Files in a Directory:
The following code shows how you can recursively delete a directory by walking the file tree. It does not follow symbolic links. I have overridden the visitFile and postVisitDirectory methods in SimpleFileVisitor so that when a file is visited, it is deleted and after all the files in the directory have been visited, the directory is deleted.

import java.io.IOException;
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;
import static java.nio.file.FileVisitResult.*;

Path dir = Paths.get("/tmp/foo");
try {
  Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {

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

          System.out.println("Deleting file: " + file);
          Files.delete(file);
          return CONTINUE;
      }

      @Override
      public FileVisitResult postVisitDirectory(Path dir,
              IOException exc) throws IOException {

          System.out.println("Deleting dir: " + dir);
          if (exc == null) {
              Files.delete(dir);
              return CONTINUE;
          } else {
              throw exc;
          }
      }

  });
} catch (IOException e) {
  e.printStackTrace();
}

1 comment:

Note: Only a member of this blog may post a comment.