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
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:
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.
📖 Sample answer from dan1st