Files.delete()
Deletes a file or an empty folder. deleteIfExists() does not throw if the file is missing.
Available since: Java 7
Syntax
static void delete(Path path) throws IOExceptionParameters
| Parameter | Type | Description |
|---|---|---|
| path | Path | What to delete. |
Return value
voidNothing.
Examples
Deleting, then deleting again:
void main() throws IOException {
Path tmp = Path.of("tmp.txt");
Files.writeString(tmp, "x");
Files.delete(tmp);
IO.println(Files.deleteIfExists(tmp));
try {
Files.delete(tmp);
} catch (NoSuchFileException e) {
IO.println("already deleted: " + e.getMessage());
}
}Output:
false
already deleted: tmp.txtNotes
Deletion is permanent — the file does not go to the recycle bin. A non-empty folder is not deleted: you get DirectoryNotEmptyException; delete its contents first (for example, walk it with Files.walk() in reverse order).
See also
- Files.exists() — Checks whether a file or folder exists. Related: isDirectory(), isRegularFile(), size().
- Files.writeString() — Writes a string to a file, creating or overwriting it.
- Files.list() — Returns a stream of the files and folders inside a folder (not nested). Files.walk() goes recursively.
Related recipes
In the tutorial
- Files and paths — Working with the file system in Java — Path, Files.exists, creating folders and files, size, copying, moving, deleting and listing files.