Delete a directory in Java

Description

The following code shows how to delete a directory.

Example


//www.j  av a  2  s .  c o m
import java.io.File;
import java.io.IOException;

public class Main {
  /**
   * 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;
  }
}




















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip