Java Directory Delete nio deleteDirectorySelectively(Path path, Predicate predicate)

Here you can find the source of deleteDirectorySelectively(Path path, Predicate predicate)

Description

delete Directory Selectively

License

Open Source License

Declaration

public static void deleteDirectorySelectively(Path path, Predicate<Path> predicate) 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;

import java.util.function.Predicate;

public class Main {
    public static void deleteDirectorySelectively(Path path, Predicate<Path> predicate) throws IOException {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override/*from   www. j a v  a  2 s  .c  o  m*/
            public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
                if (predicate.test(file)) {
                    Files.delete(file);
                }

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path directory, IOException ex) throws IOException {
                if (ex != null) {
                    return FileVisitResult.TERMINATE;
                }

                if (predicate.test(directory)) {
                    Files.delete(directory);
                }

                return FileVisitResult.CONTINUE;
            }
        });
    }
}

Related

  1. deleteDirectory(Path path)
  2. deleteDirectory(String path)
  3. deleteDirectoryAndContents(String dir)
  4. deleteDirectoryRecursively(Path dir)
  5. deleteDirectoryRecursively(Path path)
  6. deleteDirIfEmpty(Path dir)
  7. deleteDirIfExists(Path dirPath)
  8. deleteDirOrFile(Path p, boolean followSymLinkDir)
  9. deleteDirReqursivelyIfExists(File dir)