Java Path Remove nio removeDirectory(String pathToDir)

Here you can find the source of removeDirectory(String pathToDir)

Description

Remove directory and all its sub-resources with specified path

License

Open Source License

Declaration

public static boolean removeDirectory(String pathToDir) 

Method Source Code


//package com.java2s;

import java.io.File;

public class Main {
    /** Remove directory and all its sub-resources with specified path */
    public static boolean removeDirectory(String pathToDir) {
        return deleteRecursive(new File(pathToDir));
    }/*from w ww.  j  av  a 2s  .co  m*/

    /**
     * Remove specified file or directory.
     *
     * @param fileOrDirectory
     *         the file or directory to cancel
     * @return <code>true</code> if specified File was deleted and <code>false</code> otherwise
     */
    public static boolean deleteRecursive(File fileOrDirectory) {
        if (fileOrDirectory.isDirectory()) {
            File[] list = fileOrDirectory.listFiles();
            if (list == null) {
                return false;
            }
            for (File f : list) {
                if (!deleteRecursive(f)) {
                    return false;
                }
            }
        }
        return !fileOrDirectory.exists() || fileOrDirectory.delete();
    }

    /**
     * Remove specified file or directory.
     *
     * @param fileOrDirectory
     *         the file or directory to cancel
     * @param followLinks
     *         are symbolic links followed or not?
     * @return <code>true</code> if specified File was deleted and <code>false</code> otherwise
     */
    public static boolean deleteRecursive(File fileOrDirectory, boolean followLinks) {
        if (fileOrDirectory.isDirectory()) {
            // If fileOrDirectory represents a symbolic link to a folder,
            // do not read a target folder content. Just remove this symbolic link.
            if (!followLinks && java.nio.file.Files.isSymbolicLink(fileOrDirectory.toPath())) {
                return !fileOrDirectory.exists() || fileOrDirectory.delete();
            }
            File[] list = fileOrDirectory.listFiles();
            if (list == null) {
                return false;
            }
            for (File f : list) {
                if (!deleteRecursive(f, followLinks)) {
                    return false;
                }
            }
        }
        return !fileOrDirectory.exists() || fileOrDirectory.delete();
    }
}

Related

  1. appendOrRemove(LinkedList paths, DirectoryStream ds)
  2. recursiveRemoveFolder(Path folderPath)
  3. removeDirectory(Path directory)
  4. removeDirectory(Path directory)
  5. removeDirectoryIfItIsEmpty(Path directoryToRemove)
  6. removeDriveLetter(Path path)
  7. removeFile(final String removePath)
  8. removeFile(String path)