00:00

How to Delete a File in Java: All Ways with Examples

Last updated:

Clearing caches, removing expired exports and cleaning up temporary files all require deleting files. Deletion cannot be undone, so it pays to know exactly how each Java method behaves when something goes wrong.

This tutorial shows every common way to delete files and folders in Java 25, each with a tested example.

1. What Is Deleting a File in Java?

Deleting removes a file or an empty folder from the file system. Java does not move it to the recycle bin; it is gone. Deletion can fail if the path does not exist, if a folder still contains entries, or if the file is in use or protected.

2. Ways to Delete at a Glance

WayIf nothing existsIf a folder is not emptySince
Files.delete(path)Throws NoSuchFileExceptionThrows DirectoryNotEmptyExceptionJava 7
Files.deleteIfExists(path)Returns falseThrows DirectoryNotEmptyExceptionJava 7
file.delete()Returns falseReturns falseJava 1.0
Files.walk() + delete()ThrowsDeletes everything, deepest firstJava 8

3. Using Files.delete()

The recommended method deletes a path and tells you exactly why if it cannot.

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

public class DeleteWithFilesDelete {
    public static void main(String[] args) throws IOException {
        Path cache = Files.createTempFile("cache", ".dat");

        Files.delete(cache);
        System.out.println("Deleted: " + Files.notExists(cache));
        try {
            Files.delete(cache);                                   // already gone
        } catch (NoSuchFileException e) {
            System.out.println("Second delete: NoSuchFileException");
        }
    }
}
Output
Deleted: true
Second delete: NoSuchFileException

How it works

  1. Files.delete() removes the file.
  2. Deleting it again throws NoSuchFileException, which names the problem instead of failing silently.

4. Using Files.deleteIfExists()

When a missing file is not an error, for example an optional lock file, use deleteIfExists().

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

public class DeleteIfExists {
    public static void main(String[] args) throws IOException {
        Path session = Files.createTempFile("session", ".lock");

        System.out.println("First call:  " + Files.deleteIfExists(session));   // true: deleted
        System.out.println("Second call: " + Files.deleteIfExists(session));   // false: nothing to delete
    }
}
Output
First call:  true
Second call: false

How it works

  1. It returns true if it deleted something.
  2. It returns false instead of throwing when the file does not exist.

5. Using File.delete()

The classic File.delete() reports every failure as false.

DeleteWithFileDelete.java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class DeleteWithFileDelete {
    public static void main(String[] args) throws IOException {
        File folder = Files.createTempDirectory("exports").toFile();
        File report = new File(folder, "report.csv");
        report.createNewFile();

        System.out.println("Delete non-empty folder: " + folder.delete());   // false: not empty
        System.out.println("Delete file:            " + report.delete());    // true
        System.out.println("Delete empty folder:    " + folder.delete());    // true
    }
}
Output
Delete non-empty folder: false
Delete file:            true
Delete empty folder:    true

How it works

  1. Deleting a folder that still contains a file returns false.
  2. After the file is removed, the empty folder can be deleted.
  3. Because the reason for a failure is lost, prefer Files.delete() in new code.

6. Deleting a Folder and Everything in It

Java has no single method that deletes a non-empty folder. Walk the tree and delete the deepest paths first.

DeleteFolderTree.java
import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

public class DeleteFolderTree {
    public static void main(String[] args) throws IOException {
        Path project = Files.createTempDirectory("old-project");
        Files.createDirectories(project.resolve("src").resolve("main"));
        Files.writeString(project.resolve("src").resolve("main").resolve("App.java"), "class App {}");
        Files.writeString(project.resolve("README.md"), "# Old project");

        try {
            Files.delete(project);
        } catch (DirectoryNotEmptyException e) {
            System.out.println("Plain delete: DirectoryNotEmptyException");
        }

        List<Path> all;
        try (Stream<Path> tree = Files.walk(project)) {
            all = tree.sorted(Comparator.reverseOrder()).toList();   // deepest paths first
        }
        for (Path p : all) {
            Files.delete(p);
        }
        System.out.println("Paths deleted: " + all.size());
        System.out.println("Project gone: " + Files.notExists(project));
    }
}
Output
Plain delete: DirectoryNotEmptyException
Paths deleted: 5
Project gone: true

How it works

  1. A plain Files.delete() on the folder throws DirectoryNotEmptyException.
  2. Files.walk() lists the folder and everything below it; it is closed by try-with-resources.
  3. Sorting in reverse order puts files and sub-folders before their parents, so every folder is empty when its turn comes.

7. Deleting When the Program Ends

file.deleteOnExit() (Java 1.2) asks the JVM to delete a file when the program ends normally. Deletion is attempted only when the JVM terminates normally, so files remain after a crash; long-running programs should delete files explicitly instead.

Delete on exit
File scratch = File.createTempFile("render", ".tmp");
scratch.deleteOnExit();      // removed when the JVM exits normally

8. Common Mistakes and Best Practices

  • Ignoring the result of File.delete(). A failed delete goes unnoticed.
  • Deleting the wrong path. Log or print the absolute path before recursive deletes.
  • Deleting non-empty folders directly. Delete their contents first, deepest first.
  • Deleting files that are still open. Close streams first; on Windows, open files cannot be deleted.
  • Following symbolic links unintentionally. Files.walk() does not follow links by default; keep it that way when deleting.

9. Summary

  • Files.delete() deletes and throws a descriptive exception on failure.
  • Files.deleteIfExists() treats a missing file as normal.
  • File.delete() only returns true or false.
  • Delete non-empty folders with Files.walk() in reverse order.
  • Use deleteOnExit() only for short-lived temporary files.

Related Tutorials

10. Official Java Documentation References