Library contents

Java Files.delete and deleteIfExists

Remove an entry or perform cleanup that tolerates a missing file.

A simple example

Files.delete and deleteIfExists

  1. Start with A practice file exists
  2. Do this Delete that file
  3. Result The path is absent
Testing the same path after successful deletion finds no entry.

Syntax

Java 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.java

Clear 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.

First output linetrue
Main.java
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);
            }
        }
    }
}
Output
true
false

The required deletion would throw if it failed. The two optional attempts report their different outcomes.

Advertisements

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.

Resulttrue
Main.java
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);
            }
        }
    }
}
Output
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?

GivenFile contents “clay”
Worked resultRemoved

What to watch for

A directory must be empty before deletion. deleteIfExists can still throw if the file is busy or access is denied.

Documentation for Files.delete and deleteIfExists