Java Delete File Recursively deleteRecursivelyAtLeastOnExit(final File directory)

Here you can find the source of deleteRecursivelyAtLeastOnExit(final File directory)

Description

Deletes a directory recursively, falling back to deleteOnExit().

License

Open Source License

Parameter

Parameter Description
directory the directory to delete recursively

Return

whether the directory was deleted successfully

Declaration

public static boolean deleteRecursivelyAtLeastOnExit(final File directory) 

Method Source Code


//package com.java2s;

import java.io.File;

public class Main {
    /**/*from  w w  w .j  a v a 2s  . co  m*/
     * Deletes a directory recursively, falling back to deleteOnExit().
     * 
     * Thanks to Windows' incredibly sophisticated and intelligent file
     * locking, we cannot delete files that are in use, even if they are
     * "in use" by, say, a ClassLoader that is about to be garbage
     * collected.
     * 
     * For single files, Java's API has the File#deleteOnExit method, but
     * it does not perform what you'd think it should do on directories.
     * 
     * To be able to clean up directories reliably, we introduce this
     * function which tries to delete all files and directories directly,
     * falling back to deleteOnExit.
     * 
     * @param directory the directory to delete recursively
     * @return whether the directory was deleted successfully
     */
    public static boolean deleteRecursivelyAtLeastOnExit(final File directory) {
        boolean result = true;
        final File[] list = directory.listFiles();
        if (list != null) {
            for (final File file : list) {
                if (file.isDirectory()) {
                    if (!deleteRecursivelyAtLeastOnExit(file)) {
                        result = false;
                    }
                    continue;
                }
                if (!file.delete()) {
                    file.deleteOnExit();
                    result = false;
                }
            }
        }
        if (!result || !directory.delete()) {
            directory.deleteOnExit();
            result = false;
        }
        return result;
    }
}

Related

  1. deleteRecursively(File root, boolean deleteRoot)
  2. deleteRecursively(File[] roots)
  3. deleteRecursively(final File directory)
  4. deleteRecursively(final File directory)
  5. deleteRecursively(final File iRootFile)
  6. deleteRecursivelyWithoutDeleteRootDirectory(File pFile)
  7. deleteRecusively(File file)