Java File Delete nio deleteRecursive(File fileOrDirectory)

Here you can find the source of deleteRecursive(File fileOrDirectory)

Description

Remove specified file or directory.

License

Open Source License

Parameter

Parameter Description
fileOrDirectory the file or directory to cancel

Return

true if specified File was deleted and false otherwise

Declaration

public static boolean deleteRecursive(File fileOrDirectory) 

Method Source Code


//package com.java2s;

import java.io.File;

public class Main {
    /**/*from   w w w  .  j  a  v a2 s. c  om*/
     * 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. deleteLocalFile(final String fileName)
  2. deleteLocalFileOrDirectory(File file)
  3. deleteMatching(File baseFile, String regex)
  4. deletePidFile()
  5. deleteQuietly(File file)
  6. deleteRecursively(File fileOrDir)
  7. deleteRecursively(File root)
  8. deleteTestFile(String extension)
  9. forceDelete(File file)