Java File Path Delete deleteDir(File dir)

Here you can find the source of deleteDir(File dir)

Description

Recursively deletes a directory.

License

Open Source License

Parameter

Parameter Description
directory The file corresponding to a directory

Return

Whether or not the recursive delete succeeded

Declaration

public static boolean deleteDir(File dir) 

Method Source Code

//package com.java2s;

import java.io.File;

public class Main {
    /**//from  w  ww .  j  av a 2  s  . com
     * Recursively deletes a directory.
     * 
     * @param directory The file corresponding to a directory
     * 
     * @return Whether or not the recursive delete succeeded
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();

            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));

                if (!success) {
                    return false;
                }
            }
        }

        boolean isDeleted = dir.delete();
        if (!isDeleted && dir.exists()) {
            // Directories mounted on NFS volumes may have lingering .nfsXXXX files 
            // pointing to deleted files which are still referenced by the JVM.  We don't
            // explicitly have any handles open, however it appears some are created during
            // the listing above, or in some other unknown way. It seems it is possible to
            // free them by cleaning up stale objects, and giving the OS time to cleanup as 
            // well.
            System.gc();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // ignored
            }
            isDeleted = dir.delete();
        }

        return isDeleted;
    }
}

Related

  1. deleteDir(File dir)
  2. deleteDir(File dir)
  3. deleteDir(File dir)
  4. deleteDir(File dir)
  5. deleteDir(File dir)
  6. deleteDir(File dir)
  7. deleteDir(File dir)
  8. deleteDir(File dir)
  9. deleteDir(File dir)