Easy Tutorial
❮ Method Label Java Hashtable Class ❯

Java Example - Deleting a Directory

Java Examples

The following example demonstrates how to delete a directory after deleting its files one by one using the ofdir.isDirectory(), dir.list(), and deleteDir() methods of the File class:

Main.java File

import java.io.File;

public class Main {
    public static void main(String[] argv) throws Exception {
        // Delete the 'test' directory in the current directory
        deleteDir(new File("./test"));
    }
    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;
                }
            }
        }
        if (dir.delete()) {
            System.out.println("Directory has been deleted!");
            return true;
        } else {
            System.out.println("Failed to delete the directory!");
            return false;
        }
    }
}

The output of the above code is:

Directory has been deleted!

Java Examples

❮ Method Label Java Hashtable Class ❯