How to Delete a File in Java: All Ways with Examples
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
| Way | If nothing exists | If a folder is not empty | Since |
|---|---|---|---|
Files.delete(path) | Throws NoSuchFileException | Throws DirectoryNotEmptyException | Java 7 |
Files.deleteIfExists(path) | Returns false | Throws DirectoryNotEmptyException | Java 7 |
file.delete() | Returns false | Returns false | Java 1.0 |
Files.walk() + delete() | Throws | Deletes everything, deepest first | Java 8 |
3. Using Files.delete()
The recommended method deletes a path and tells you exactly why if it cannot.
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");
}
}
}
Deleted: true Second delete: NoSuchFileException
How it works
Files.delete()removes the file.- 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().
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
}
}
First call: true Second call: false
How it works
- It returns
trueif it deleted something. - It returns
falseinstead of throwing when the file does not exist.
5. Using File.delete()
The classic File.delete() reports every failure as false.
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
}
}
Delete non-empty folder: false Delete file: true Delete empty folder: true
How it works
- Deleting a folder that still contains a file returns
false. - After the file is removed, the empty folder can be deleted.
- 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.
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));
}
}
Plain delete: DirectoryNotEmptyException Paths deleted: 5 Project gone: true
How it works
- A plain
Files.delete()on the folder throwsDirectoryNotEmptyException. Files.walk()lists the folder and everything below it; it is closed by try-with-resources.- 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.
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 returnstrueorfalse.- Delete non-empty folders with
Files.walk()in reverse order. - Use
deleteOnExit()only for short-lived temporary files.