Java Files delete() Method

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

Definition

In Java, Files.delete(path) removes a file, an empty folder, or a symbolic link. It returns nothing; if it returns normally, the entry is gone.

It is strict: a missing path throws NoSuchFileException, and a folder that still has entries throws DirectoryNotEmptyException. That strictness helps you notice mistakes; use deleteIfExists when "already gone" is fine.

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.delete(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

Pass the path to remove:

Java
Files.delete(dir.resolve("old.log"));    // file
Files.delete(emptyFolder);                // folder must be empty
Files.delete(link);                       // removes the link, not its target
CallWhat it does
Files.delete(p)Removes p; throws if missing.
Files.deleteIfExists(p)Same, but returns false when missing.
file.toFile().delete()Old java.io way; returns false on any failure.

Since Java 7. There is no recursive delete in Files; empty a folder first (Example 2) or walk it in reverse order.

Library declarations
Java
public static void delete(Path path) throws IOException

Parameters

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

Return Value

Return ValueDescription
voidNothing. Success means the entry was deleted.

Compare with Similar Methods

Removing things:

MethodHow it differs
deleteIfExists()No exception for a missing path; returns a boolean.
walkFileTree()Visit a tree and delete folders after their contents.
move()Relocate instead of removing.

Java Examples

Example 1 — Delete a File and an Empty Folder

Delete both kinds of entry, then show that deleting the same file again throws.

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

public class DeleteBasic {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path log = Files.createFile(dir.resolve("old.log"));
        Path empty = Files.createDirectory(dir.resolve("empty"));
        Files.delete(log);
        System.out.println("old.log exists: " + Files.exists(log));
        Files.delete(empty);
        System.out.println("empty folder exists: " + Files.exists(empty));
        try {
            Files.delete(log);
        } catch (NoSuchFileException e) {
            System.out.println("Deleting old.log again: NoSuchFileException");
        }
        Files.delete(dir);
    }
}

How It Works

  1. No return value to check. delete is void; reaching the next line means the file is gone, which exists confirms.
  2. Folders too. The empty folder is removed by the very same call.
  3. Strict about absence. The second attempt on old.log finds nothing and throws NoSuchFileException, a hint that the program's idea of the disk was wrong.

Example 2 — Delete a Non-Empty Folder Recursively

A full folder cannot be deleted directly. A small recursive helper empties each folder before deleting it.

Java
import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class DeleteTree {
    static int deleteTree(Path p) throws IOException {
        int count = 0;
        if (Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS)) {
            List<Path> children = new ArrayList<>();
            try (DirectoryStream<Path> entries = Files.newDirectoryStream(p)) {
                for (Path child : entries) {
                    children.add(child);
                }
            }
            for (Path child : children) {
                count += deleteTree(child);
            }
        }
        Files.delete(p);
        return count + 1;
    }

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path year = Files.createDirectories(dir.resolve("logs").resolve("2026"));
        Files.createFile(year.resolve("jan.log"));
        Files.createFile(year.resolve("feb.log"));
        try {
            Files.delete(dir.resolve("logs"));
        } catch (DirectoryNotEmptyException e) {
            System.out.println("logs: DirectoryNotEmptyException");
        }
        System.out.println("Entries deleted: " + deleteTree(dir));
        System.out.println("Temp folder gone: " + Files.notExists(dir));
    }
}

How It Works

  1. The direct attempt fails. logs still contains 2026 and two log files, so Files.delete throws DirectoryNotEmptyException and deletes nothing.
  2. Collect, close, then delete. The helper copies the children into a list and closes the directory stream before deleting anything, which avoids surprises on Windows.
  3. Do not follow links. NOFOLLOW_LINKS makes a symbolic link to a folder count as a plain entry, so the helper deletes the link and never wanders into the target.
  4. Count on the way back. Each call deletes its own entry last and adds one: two files, 2026, logs, and the temp folder make 5.

Example 3 — Report What Happened for Each Path

Try to delete three paths and catch the two typical failures separately.

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

public class DeleteOutcomes {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path file = Files.createFile(dir.resolve("a.txt"));
        Path full = Files.createDirectory(dir.resolve("full"));
        Path inner = Files.createFile(full.resolve("b.txt"));
        Path[] targets = {file, dir.resolve("ghost.txt"), full};
        for (Path p : targets) {
            String name = p.getFileName().toString();
            try {
                Files.delete(p);
                System.out.println(name + ": deleted");
            } catch (NoSuchFileException e) {
                System.out.println(name + ": not found");
            } catch (DirectoryNotEmptyException e) {
                System.out.println(name + ": folder not empty");
            }
        }
        Files.delete(inner);
        Files.delete(full);
        Files.delete(dir);
    }
}

How It Works

  1. Three different situations. a.txt exists, ghost.txt was never created, and full holds b.txt.
  2. One catch per cause. Both exceptions extend FileSystemException, but catching them separately lets the program print a precise message for each path.
  3. Finish the job. After the loop, b.txt is deleted first, so full is empty and can go, followed by the temp folder.

Frequently Asked Questions

It throws NoSuchFileException. Use Files.deleteIfExists if a missing file is acceptable.
Delete its contents first. Walk the tree with Files.walk sorted in reverse order, use Files.walkFileTree and delete folders in postVisitDirectory, or write a small recursive helper.
No. It deletes the symbolic link itself and leaves the target untouched.
Usually because another program, or an unclosed stream in your own program, still has the file open, or because the file is read-only. Close all streams with try-with-resources first.
File.delete returns false on any failure without a reason. Files.delete throws NoSuchFileException, DirectoryNotEmptyException, or another IOException that explains what went wrong.

Next: Files.deleteIfExists()

Delete a file or empty folder if it exists; returns true if something was deleted.

deleteIfExists() 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.

15 people found this page helpful