Java Path Delete nio deleteRecursively(final Path path)

Here you can find the source of deleteRecursively(final Path path)

Description

delete Recursively

License

Common Public License

Declaration

public static void deleteRecursively(final Path path) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Common Public 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 {
    public static void deleteRecursively(final Path path) throws IOException {
        deleteRecursively(path, true);/*from www.j  a va  2s.c o  m*/
    }

    public static void deleteRecursively(final Path path, final boolean deleteSelf) throws IOException {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                // Delete file
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                // Try to delete anyway
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (exc == null) {
                    // Delete directory (unless self)
                    if (deleteSelf || !dir.equals(path)) {
                        Files.delete(dir);
                    }
                    return FileVisitResult.CONTINUE;
                } else {
                    throw exc;
                }
            }
        });
    }
}

Related

  1. deletePathRecursively(String path)
  2. deleteQuietly(@Nullable Path path)
  3. deleteQuietly(Path dir)
  4. deleteRecursive(Path path)
  5. deleteRecursive(Path path)
  6. deleteRecursively(Path directory)
  7. deleteRecursively(Path path)
  8. deleteTmpDir(Path path)
  9. deleteTreeBelowPath(Path startHerePath)