Java Directory Delete nio deleteDirOrFile(Path p, boolean followSymLinkDir)

Here you can find the source of deleteDirOrFile(Path p, boolean followSymLinkDir)

Description

remove given file or dir.

License

Open Source License

Declaration

public static void deleteDirOrFile(Path p, boolean followSymLinkDir) throws IOException 

Method Source Code

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

import java.io.IOException;

import java.nio.file.FileVisitOption;
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;
import java.util.EnumSet;

import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.SKIP_SUBTREE;

public class Main {
    /**/*  ww  w . j  av  a 2 s  . c  o  m*/
     * remove given file or dir.
     */
    public static void deleteDirOrFile(Path p, boolean followSymLinkDir) throws IOException {
        if (p == null || !Files.exists(p))
            return;

        if (!Files.isDirectory(p))
            Files.delete(p);
        else
            Files.walkFileTree(p, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                    new SimpleFileVisitor<Path>() {
                        @Override
                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                            Files.delete(file);
                            return CONTINUE;
                        }

                        @Override
                        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                                throws IOException {
                            if (Files.isSymbolicLink(dir) && !followSymLinkDir) {
                                Files.delete(dir);
                                return SKIP_SUBTREE;
                            } else
                                return CONTINUE;
                        }

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

    /**
     * remove given file or dir. not follow symbolic link dir by default.
     */
    public static void deleteDirOrFile(Path path) throws IOException {
        deleteDirOrFile(path, false);
    }
}

Related

  1. deleteDirectoryRecursively(Path dir)
  2. deleteDirectoryRecursively(Path path)
  3. deleteDirectorySelectively(Path path, Predicate predicate)
  4. deleteDirIfEmpty(Path dir)
  5. deleteDirIfExists(Path dirPath)
  6. deleteDirReqursivelyIfExists(File dir)
  7. deleteDirWithFiles(File dir, int maxDepth)
  8. deleteFileOrDirectory(File file)
  9. deleteFileOrDirectory(final File source)