Mega Code Archive

 
Categories / Java / File Input Output
 

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;   } }