Video in progress
How do you delete a directory with everything in it, and what mistakes come up here?
Files.delete only deletes an empty directory. For recursive deletion you delete the result of Files.walk in reverse order, or use Files.walkFileTree and delete the directory in postVisitDirectory. It matters not to follow symlinks and to choose whether to stop on an error.
📖 Answer
The shortest version:
try (Stream<Path> s = Files.walk(root)) {
s.sorted(Comparator.reverseOrder()) // contents first, then directories
.forEach(p -> {
try { Files.delete(p); }
catch (IOException e) { throw new UncheckedIOException(e); }
});
}
Reverse order is needed because walk gives the directory first and then its contents. The downside of this code: everything stops at the first error, and sorted collects the whole list in memory.
For many files and error tolerance, walkFileTree is more convenient:
Files.walkFileTree(root, new SimpleFileVisitor<>() {
@Override public FileVisitResult visitFile(Path f, BasicFileAttributes a) throws IOException {
Files.delete(f);
return FileVisitResult.CONTINUE;
}
@Override public FileVisitResult postVisitDirectory(Path d, IOException e) throws IOException {
if (e != null) throw e;
Files.delete(d);
return FileVisitResult.CONTINUE;
}
});
What causes trouble:
- Symlinks. By default
walkandwalkFileTreedon't follow links, so the link itself is deleted, not the directory it points to. If you addFOLLOW_LINKS, a link like/tmp/job/data -> /var/lib/appcan wipe out all the data. - Windows. A file that is open or has a read-only attribute can't be deleted:
AccessDeniedException. - Parallel changes. If another process adds a file during the walk, the directory is no longer empty (
DirectoryNotEmptyException). For such directories people usually move them aside first with an atomicrenameand delete afterwards.
If you work in a directory that others can write to, there is SecureDirectoryStream against symlink-swap attacks: on Linux, Files.newDirectoryStream returns that type.
Sign up to mark studied questions and save your progress.