Java Directory Delete nio deleteDirectoryRecursively(Path dir)

Here you can find the source of deleteDirectoryRecursively(Path dir)

Description

Delete a directory recursively.

License

Open Source License

Parameter

Parameter Description
dir the directory to delete

Exception

Parameter Description
IOException if an error occurs

Declaration

public static void deleteDirectoryRecursively(Path dir) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;

import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
    /**/*from  w w w. j a  v a  2s  .  c om*/
     * Delete a directory recursively.
     *
     * @param dir the directory to delete
     * @throws IOException if an error occurs
     */
    public static void deleteDirectoryRecursively(Path dir) throws IOException {
        if (!Files.exists(dir)) {
            return;
        }
        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

Related

  1. deleteDirectory(Path directory)
  2. deleteDirectory(Path dirToDelete)
  3. deleteDirectory(Path path)
  4. deleteDirectory(String path)
  5. deleteDirectoryAndContents(String dir)
  6. deleteDirectoryRecursively(Path path)
  7. deleteDirectorySelectively(Path path, Predicate predicate)
  8. deleteDirIfEmpty(Path dir)
  9. deleteDirIfExists(Path dirPath)