Java Directory Delete nio deleteDirectory(Path directory)

Here you can find the source of deleteDirectory(Path directory)

Description

Deletes a directory recursively

License

Apache License

Parameter

Parameter Description
directory a parameter

Return

true if deletion succeeds, false otherwise

Declaration

public static boolean deleteDirectory(Path directory) 

Method Source Code


//package com.java2s;
//License from project: Apache 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 ww.java2 s  .com*/
     * Deletes a directory recursively
     *
     * @param directory
     * @return true if deletion succeeds, false otherwise
     */
    public static boolean deleteDirectory(Path directory) {
        if (directory != null) {
            try {
                Files.walkFileTree(directory, 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;
                    }
                });
            } catch (IOException ignored) {
                return false;
            }
        }
        return true;
    }
}

Related

  1. deleteDirectory(final Path dir, final int maxDepth)
  2. deleteDirectory(Path dir)
  3. deleteDirectory(Path directory)
  4. deleteDirectory(Path directory)
  5. deleteDirectory(Path directory)
  6. deleteDirectory(Path dirToDelete)
  7. deleteDirectory(Path path)
  8. deleteDirectory(String path)
  9. deleteDirectoryAndContents(String dir)