The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.io  [35 examples] > Directories  [6 examples]

e30. Deleting a Directory

    // Delete an empty directory
    boolean success = (new File("directoryName")).delete();
    if (!success) {
        // Deletion failed
    }
If the directory is not empty, it is necessary to first recursively delete all files and subdirectories in the directory. Here is a method that will delete a non-empty directory.
    // Deletes all files and subdirectories under dir.
    // Returns true if all deletions were successful.
    // If a deletion fails, the method stops attempting to delete and returns false.
    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;
                }
            }
        }
    
        // The directory is now empty so delete it
        return dir.delete();
    }

 Related Examples
e28. Getting the Current Working Directory
e29. Creating a Directory
e31. Listing the Files or Subdirectories in a Directory
e32. Listing the File System Roots
e33. Traversing the Files and Directories Under a Directory

See also: Encodings    Filenames and Pathnames    Files    Parsing    Reading and Writing    Serialization   


© 2002 Addison-Wesley.