Course contentsShow
← Java
Lesson 2062 of 2,87041. NIO.2 and the Path APIFree lesson

DirectoryNotEmptyException: Handling Non-Empty Directories

Understand why deleting non-empty directories fails and how to handle DirectoryNotEmptyException.

DirectoryNotEmptyException: Handling Non-Empty Directories

You'll learn why directory deletion fails when a directory contains files and how to catch and handle this specific exception.

Why Directory Deletion Fails

When you try to delete a directory using Files.delete() or Files.deleteIfExists(), Java will throw a DirectoryNotEmptyException if the directory still contains files or subdirectories. Think of it like trying to throw away a box—you can't recycle the box if it still has items inside.

The NIO.2 API enforces this as a safety mechanism. Accidentally deleting an entire directory tree could destroy important data, so Java requires you to explicitly handle this scenario.

Understanding the Exception

DirectoryNotEmptyException is a checked exception that extends IOException. It signals that the directory you're attempting to delete isn't empty. Unlike simpler file systems operations, Java won't automatically delete contents recursively—you must do that intentionally.

Handling the Exception

Path directory = Paths.get("myFolder");

try {
    Files.delete(directory);
    System.out.println("Directory deleted successfully");
} catch (DirectoryNotEmptyException e) {
    System.err.println("Cannot delete: directory contains files");
    // Handle appropriately: list contents, ask user, etc.
} catch (IOException e) {
    System.err.println("Other I/O error: " + e.getMessage());
}

When you catch DirectoryNotEmptyException, you have options: inform the user, programmatically delete contents first (manually iterating and deleting each file), or simply abort the operation. The key is recognizing that this exception indicates a deliberate design choice requiring explicit handling.

Key Takeaway: DirectoryNotEmptyException prevents accidental data loss by forcing you to explicitly handle attempts to delete non-empty directories—catch it separately to distinguish this case from other I/O failures.