Video in progress
Should you check with Files.exists() before deleting a file?
You don't have to, and it can even be wrong: the file can change between the check and the delete. The right way is to call Files.deleteIfExists(path), or catch Files.delete and handle NoSuchFileException.
📖 Answer
You see this code a lot:
if (Files.exists(tmp)) {
Files.delete(tmp); // if another thread deleted it in the meantime: exception
}
The problem is "check-then-act": the check and the action are not atomic. With a single user you won't see it, but under load it fails from time to time.
Simpler and more correct:
boolean deleted = Files.deleteIfExists(tmp);
One more thing: Files.exists and Files.notExists can both return false, for example if you have no read permission on the directory. So "doesn't exist" is not the same as "couldn't find out".
Files.delete does not delete a non-empty directory (DirectoryNotEmptyException); you first have to delete its contents with Files.walk.
Sign up to mark studied questions and save your progress.