Week 101 — How can a directory be deleted from Java code including subdirectories and files?

Question of the Week #101
How can a directory be deleted from Java code including subdirectories and files?
1 Reply
dan1st | Daniel
Files and directories can be deleted using the Files.delete method, e.g. using Files.delete(Path.of("/path/to/file"));. However, this only works for files and empty directories. To delete directories with contents, one first needs to delete all contents of that directory. Since a directory might have non-empty subdirectories, these need to be deleted recursively. To do that, one can use Files.list() to get a list of all files in the directory to delete and then call the method recursively for all found directories. After processing the content of a directory, it can be deleted:
public static void deleteDirectory(Path toDelete) throws IOException {
List<Path> entriesToDelete;
try(Stream<Path> entries = Files.list(toDelete)) {
for(Path entry : entriesToDelete.toList()) {
if(Files.isDirectory(entry)){
deleteDirectory(entry);
} else {
Files.delete(entry);
}
}
Files.delete(toDelete);
}
}
public static void deleteDirectory(Path toDelete) throws IOException {
List<Path> entriesToDelete;
try(Stream<Path> entries = Files.list(toDelete)) {
for(Path entry : entriesToDelete.toList()) {
if(Files.isDirectory(entry)){
deleteDirectory(entry);
} else {
Files.delete(entry);
}
}
Files.delete(toDelete);
}
}
Alternatively, it is possible to use Files.walk which recursively traverses the directory. Since that method finds the parent directories first, it is necessary to reverse the elements before iterating which can be done using the List#reversed method that has been added in JDK 21.
public static void deleteDirectory(Path toDelete) throws IOException {
try(Stream<Path> entries = Files.walk(toDelete)){
for(Path entry : entries.toList().reversed()) {
Files.delete(entry);
}
}
}
public static void deleteDirectory(Path toDelete) throws IOException {
try(Stream<Path> entries = Files.walk(toDelete)){
for(Path entry : entries.toList().reversed()) {
Files.delete(entry);
}
}
}
📖 Sample answer from dan1st
Want results from more Discord servers?
Add your server