Java : DirectoryNotEmptyException with Examples

DirectoryNotEmptyException (Java SE 22 & JDK 22) in Java with Examples.
You will find code samples for most of the DirectoryNotEmptyException methods.


Summary

Checked exception thrown when a file system operation fails because a directory is not empty.

Class diagram

For example, a DirectoryNotEmptyException is thrown when trying to delete a directory with contents.

Please see also : Delete a directory with contents

final var dir = Path.of("R:", "java-work", "dir");
System.out.println(dir); // R:\java-work\dir

final var file = dir.resolve(Path.of("aaa.txt"));
System.out.println(file); // R:\java-work\dir\aaa.txt

Files.createDirectories(dir);
Files.createFile(file);

// --- PowerShell ---
//PS R:\java-work> tree /F
//...
//R:.
//└─dir
//        aaa.txt

// --- NG ---
try {
    System.out.println("-- delete --");
    Files.delete(dir);
} catch (DirectoryNotEmptyException e) {
    System.out.println(e);
}

// Result
// ↓
//-- delete --
//java.nio.file.DirectoryNotEmptyException: R:\java-work\dir

// --- OK ---
Files.delete(file);
Files.delete(dir);

System.out.println(Files.notExists(dir)); // true
final var src = Path.of("R:", "java-work", "src-dir");
final var dst = Path.of("R:", "java-work", "dst-dir");

System.out.println(src); // R:\java-work\src-dir
System.out.println(dst); // R:\java-work\dst-dir

Files.createDirectories(src);
Files.createDirectories(dst);
Files.createFile(dst.resolve(Path.of("aaa.txt")));

// --- PowerShell ---
//PS R:\java-work> tree /F
//...
//R:.
//├─dst-dir
//│      aaa.txt
//│
//└─src-dir

try {
    System.out.println("-- move --");
    Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING);
} catch (DirectoryNotEmptyException e) {
    System.out.println(e);
}

// Result
// ↓
//-- move --
//java.nio.file.DirectoryNotEmptyException: R:\java-work\dst-dir

Constructors

DirectoryNotEmptyException (String dir)

Constructs an instance of this class.

final var e = new DirectoryNotEmptyException("Dir!");
System.out.println(e); // java.nio.file.DirectoryNotEmptyException: Dir!
System.out.println(e.getFile()); // Dir!

Methods declared in FileSystemException

getFile, getMessage, getOtherFile, getReason

Please see the link below.

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page