Deleting a folder

Before attempting to delete a folder, we must delete all the files from it. This statement is very important since it doesn't allow us to simply call the delete()/deleteIfExists() methods for a folder that contains files. An elegant solution to this problem relies on a FileVisitor implementation that starts from the following stub:

public class DeleteFileVisitor implements FileVisitor {
...
private static boolean delete(Path file) throws IOException {

return Files.deleteIfExists(file);
}
}

Let's take a look at the main checkpoints and the implementation of deleting a folder:

  • visitFile() is the perfect place for deleting each file from the given folder or subfolder (if a file cannot be deleted, then we simply pass it to the next file, but feel free to adapt the code to suit your needs):
@Override
public FileVisitResult visitFile(
Object file, BasicFileAttributes attrs) throws IOException {

delete((Path) file);

return FileVisitResult.CONTINUE;
}
  • A folder can be deleted only if it is empty, and so postVisitDirectory() is the perfect place to do this (we ignore any potential IOException, but feel free to adapt the code to suit your needs (for example, log the names of the folders that couldn't be deleted or throw an exception to stop the process)):
@Override
public FileVisitResult postVisitDirectory(
Object dir, IOException ioe) throws IOException {

delete((Path) dir);

return FileVisitResult.CONTINUE;
}

In visitFileFailed() and preVisitDirectory(), we simply return CONTINUE.

For deleting the folder, in D:/learning, we can call DeleteFileVisitor, as follows:

Path directory = Paths.get("D:/learning");
DeleteFileVisitor deleteFileVisitor = new DeleteFileVisitor();
EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

Files.walkFileTree(directory, opts,
Integer.MAX_VALUE, deleteFileVisitor);
By combining SearchFileVisitor and DeleteFileVisitor, we can obtain a search-delete application.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset