Java Path Remove nio recursiveRemoveFolder(Path folderPath)

Here you can find the source of recursiveRemoveFolder(Path folderPath)

Description

recursive Remove Folder

License

Creative Commons License

Declaration

public static void recursiveRemoveFolder(Path folderPath) throws IOException 

Method Source Code

//package com.java2s;
/** Utility methods and constants for testing.
 * //from  www.  j a va  2 s  .  c  o  m
 * @author Iovka Boneva
 * This document is licensed under a Creative Commons Attribution 3.0 License: http://creativecommons.org/licenses/by/3.0/
 * 1 mars 2016
 */

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
    public static final String TMP_DIR = System.getProperty("java.io.tmpdir") + "/";

    public static void recursiveRemoveFolder(Path folderPath) throws IOException {

        if (!folderPath.startsWith(Paths.get(TMP_DIR))) {
            throw new IllegalArgumentException("Refuse to delete a folder that is not in the system tmpdir");
        }

        Files.walkFileTree(folderPath, new FileVisitor<Path>() {

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                System.out.println("Deleting directory: " + dir);
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                System.out.println("Deleting file: " + file);
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                System.out.println(exc.toString());
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

Related

  1. appendOrRemove(LinkedList paths, DirectoryStream ds)
  2. removeDirectory(Path directory)
  3. removeDirectory(Path directory)
  4. removeDirectory(String pathToDir)
  5. removeDirectoryIfItIsEmpty(Path directoryToRemove)