How to delete a file or folder
Short answer
Files.deleteIfExists() deletes the file and returns true, or false if there was no file:
void main() throws IOException {
Path file = Path.of("temp.txt");
Files.writeString(file, "data");
IO.println(Files.deleteIfExists(file));
IO.println(Files.deleteIfExists(file));
}Output:
true
falseStrict deletion
Files.delete() throws if the file is missing — useful when its absence means an error:
void main() throws IOException {
Files.delete(Path.of("missing.txt"));
}Output:
Exception in thread "main" java.nio.file.NoSuchFileException: missing.txtA folder with contents
You cannot delete a non-empty folder. Walk it with Files.walk() and delete from the deepest entries first:
void main() throws IOException {
Path root = Path.of("build");
Files.createDirectories(root.resolve("classes"));
Files.writeString(root.resolve("classes/App.class"), "x");
try (var paths = Files.walk(root)) {
for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(p);
}
}
IO.println(Files.exists(root));
}Output:
falseCommon mistake
Calling delete() on a non-empty folder:
void main() throws IOException {
Path dir = Files.createDirectories(Path.of("logs"));
Files.writeString(dir.resolve("a.log"), "x");
Files.delete(dir);
}Output:
Exception in thread "main" java.nio.file.DirectoryNotEmptyException: logsFiles deleted this way do not go to the recycle bin — you cannot restore them.
Functions used in this recipe
- Files.delete() — Deletes a file or an empty folder. deleteIfExists() does not throw if the file is missing.
- Files.list() — Returns a stream of the files and folders inside a folder (not nested). Files.walk() goes recursively.