Deletes a directory. : Delete « File Input Output « Java






Deletes a directory.

 
import java.io.File;
import java.io.IOException;

public class Utils {
  /**
   * Deletes a directory.
   *
   * @param dir the file for the directory to delete
   * @return true if susscess
   */
  public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
      for (File file : dir.listFiles()) {
        if (file.isDirectory()) {
          try {
            if (file.getCanonicalFile().getParentFile().equals(dir.getCanonicalFile())) {
              deleteDir(file);
              if (file.exists() && !file.delete()) {
                System.out.println("Can't delete: " + file);
              }
            } else {
              System.out.println("Warning: " + file + " may be a symlink.  Ignoring.");
            }
          } catch (IOException e) {
            System.out.println("Warning: Cannot determine canonical file for " + file + " - ignoring.");
          }
        } else {
          if (file.exists() && !file.delete()) {
            System.out.println("Can't delete: " + file);
          }
        }
      }
      return dir.delete();
    }
    return false;
  }
}

   
  








Related examples in the same category

1.Deletes all files and subdirectories
2.Remove file or directory
3.Utilities for file delete copy close
4.Deletes the diretory and any files and directories in it recursively.
5.Delete Recursively
6.Delete a file
7.Delete all files under this file and including this file
8.Delete the file or non-empty directory at the supplied path
9.Recursively delete a file and all its contents
10.Empty and delete a folder (and subfolders).