Java Files.delete and deleteIfExists
Remove an entry or perform cleanup that tolerates a missing file.
A simple example
Files.delete and deleteIfExists
- Start with A practice file exists
- Do this Delete that file
- Result The path is absent
Syntax
public static void delete(Path path) throws IOException
JDK 21 declarations (2)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaClear yesterday's practice labels
A printer station removes a mandatory draft and an optional second preview after a test. The cleaning job may run twice, so it needs to distinguish a removed optional file from one already gone.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path draft = Files.createFile(desk.resolve("draft"));
Path preview = Files.createFile(desk.resolve("preview"));
Files.delete(draft);
System.out.println(Files.deleteIfExists(preview));
System.out.println(Files.deleteIfExists(preview));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true false
The required deletion would throw if it failed. The two optional attempts report their different outcomes.
Keep a folder that still contains a receipt
An archive job should retire an empty batch folder after processing. Attempt the deletion while a receipt is still inside and verify that the receipt is preserved.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path batch = Files.createDirectory(desk.resolve("batch"));
Path receipt = Files.createFile(batch.resolve("receipt"));
try { Files.delete(batch); }
catch (DirectoryNotEmptyException e) { System.out.println(Files.exists(receipt)); }
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true
The local filesystem refuses to delete a nonempty directory through this operation.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. The desk removes the temporary note after handover. Does its original name still identify an entry?
What to watch for
A directory must be empty before deletion. deleteIfExists can still throw if the file is busy or access is denied.