Most of answers (even recent) referencing JDK classes rely on File.delete()
but that is a flawed API as the operation may fail silently.
The java.io.File.delete()
method documentation states :
Note that the
java.nio.file.Files
class defines thedelete
method to throw anIOException
when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
As replacement, you should favor Files.delete(Path p)
that throws an IOException
with a error message.
The actual code could be written such as :
Path index = Paths.get("/home/Work/Indexer1");
if (!Files.exists(index)) {
index = Files.createDirectories(index);
} else {
Files.walk(index)
.sorted(Comparator.reverseOrder()) // as the file tree is traversed depth-first and that deleted dirs have to be empty
.forEach(t -> {
try {
Files.delete(t);
} catch (IOException e) {
// LOG the exception and potentially stop the processing
}
});
if (!Files.exists(index)) {
index = Files.createDirectories(index);
}
}