Java Files deleteIfExists() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, Files.deleteIfExists(path) deletes the file, empty folder, or link at path if it exists. It returns a boolean: true when it deleted something, false when there was nothing to delete.

It removes only one worry, the missing path. A folder that is not empty still throws DirectoryNotEmptyException, and permission problems still throw IOExceptions. It is ideal for cleanup code that may run more than once.

A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.deleteIfExists(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

Same argument as delete, plus a result:

Java
boolean removed = Files.deleteIfExists(dir.resolve("cache.dat"));
// true the first time, false afterwards
CallWhat it does
Files.deleteIfExists(p)Deletes if present; true/false.
Files.delete(p)Throws NoSuchFileException instead of returning false.
if (Files.exists(p)) Files.delete(p)Racy version: the file can vanish between the two calls.

Since Java 7. The existence check and the delete happen together, so unlike an exists check followed by delete, another program removing the file in between cannot make it throw.

Library declarations
Java
public static boolean deleteIfExists(Path path) throws IOException

Parameters

ParameterDescription
pathThe file, empty folder, or link to delete if present.

Return Value

Return ValueDescription
trueThe entry existed and was deleted.
falseNothing existed at path.

Compare with Similar Methods

Choosing a delete:

MethodHow it differs
delete()Strict: a missing path is an error.
notExists()Only checks; deletes nothing.
createTempFile()Creates the files you typically clean up with this method.

Java Examples

Example 1 — See the Boolean Result

Delete the same file twice and also try a name that never existed.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class DeleteIfExistsBasic {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path cache = Files.createFile(dir.resolve("cache.dat"));
        System.out.println("First call: " + Files.deleteIfExists(cache));
        System.out.println("Second call: " + Files.deleteIfExists(cache));
        System.out.println("Never existed: " + Files.deleteIfExists(dir.resolve("nothing.dat")));
        Files.delete(dir);
    }
}

How It Works

  1. Something to delete. cache.dat exists, so the first call removes it and returns true.
  2. Nothing left. The second call finds no file and quietly returns false instead of throwing.
  3. Same for unknown names. A path that was never created also gives false, so the method is safe to call blindly.

Example 2 — Clean Up Whatever Was Created

A job creates two files, but fails before the second one. The finally block removes whatever exists, without caring which steps ran.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

public class DeleteIfExistsFinally {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path step1 = dir.resolve("step1.out");
        Path step2 = dir.resolve("step2.out");
        try {
            Files.createFile(step1);
            Files.createDirectory(dir.resolve("missing").resolve("sub"));
            Files.createFile(step2);
        } catch (NoSuchFileException e) {
            System.out.println("Middle step failed: NoSuchFileException");
        } finally {
            System.out.println("step1.out removed: " + Files.deleteIfExists(step1));
            System.out.println("step2.out removed: " + Files.deleteIfExists(step2));
            Files.delete(dir);
        }
    }
}

How It Works

  1. A failure in the middle. step1.out is created, then creating missing/sub fails because missing does not exist, so step2.out is never made.
  2. Cleanup without bookkeeping. The finally block simply calls deleteIfExists on both names; no flags are needed to remember which files were created.
  3. The results tell the story. true for the file that existed and false for the one that never did; with plain delete, the second call would have thrown inside finally.

Example 3 — Sweep a List of Names, Then Hit a Full Folder

Count how many of several possible files were removed, then show that a non-empty folder still throws.

Java
import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.Path;

public class DeleteIfExistsSweep {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Files.createFile(dir.resolve("a.tmp"));
        Files.createFile(dir.resolve("c.tmp"));
        String[] names = {"a.tmp", "b.tmp", "c.tmp"};
        int removed = 0;
        for (String n : names) {
            if (Files.deleteIfExists(dir.resolve(n))) {
                removed++;
            }
        }
        System.out.println("Removed " + removed + " of " + names.length);
        Path box = Files.createDirectory(dir.resolve("box"));
        Path item = Files.createFile(box.resolve("item.txt"));
        try {
            Files.deleteIfExists(box);
        } catch (DirectoryNotEmptyException e) {
            System.out.println("box: DirectoryNotEmptyException");
        }
        Files.deleteIfExists(item);
        Files.deleteIfExists(box);
        Files.delete(dir);
    }
}

How It Works

  1. Some present, some not. Only a.tmp and c.tmp exist; b.tmp is skipped with a false result, and the counter ends at 2.
  2. Exists is not enough. box exists, but it holds item.txt, so deleteIfExists throws DirectoryNotEmptyException just like delete would.
  3. Empty it first. Deleting item.txt makes box empty, and the next call removes it.

Frequently Asked Questions

true if the file or folder existed and was deleted, false if nothing existed at that path.
Yes. It still throws DirectoryNotEmptyException for a non-empty folder and IOException for other problems, such as missing permissions or a file locked by another program on Windows.
Yes. exists() followed by delete() can fail if another program removes the file in between. deleteIfExists does both in one step.
No. The folder must be empty. Delete its contents first, for example by walking the tree in reverse order.
Use delete when a missing file means a bug and you want an exception. Use deleteIfExists for cleanup code where the file may or may not be there.

Next: Files.exists()

Check whether a file or folder exists (following symbolic links by default).

exists() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful