Java Delete Files
Deleting Files and Folders
Deleting is the one file operation that can't be undone from Java: there is no recycle bin or trash. A deleted file is removed from its folder immediately and, unless a backup exists, its data is gone. That's why delete operations deserve careful handling — know exactly what you're deleting, and know whether it actually happened.
Java provides three main methods:
| Method | If the target doesn't exist | If deletion fails | Package |
|---|---|---|---|
Files.delete(path) | Throws NoSuchFileException | Throws a specific IOException | java.nio.file |
Files.deleteIfExists(path) | Returns false | Throws a specific IOException | java.nio.file |
file.delete() | Returns false | Returns false (no reason given) | java.io |
None of them delete a folder that still has contents. Removing a whole folder tree requires deleting its contents first, as shown later in this lesson.
Files.delete and Files.deleteIfExists
import java.io.IOException;
import java.nio.file.*;
public class D1 {
public static void main(String[] args) throws IOException {
Path file = Files.writeString(Path.of("draft.txt"), "temporary notes");
Files.delete(file);
System.out.println("deleted, exists now: " + Files.exists(file));
try {
Files.delete(file);
} catch (NoSuchFileException e) {
System.out.println("NoSuchFileException: " + e.getFile());
}
System.out.println("deleteIfExists: " + Files.deleteIfExists(file));
Files.writeString(file, "again");
System.out.println("deleteIfExists: " + Files.deleteIfExists(file));
Path dir = Files.createDirectories(Path.of("uploads"));
Files.writeString(dir.resolve("photo.jpg"), "fake image");
try {
Files.delete(dir);
} catch (DirectoryNotEmptyException e) {
System.out.println("DirectoryNotEmptyException: " + e.getFile());
}
}
}
Output:
deleted, exists now: false
NoSuchFileException: draft.txt
deleteIfExists: false
deleteIfExists: true
DirectoryNotEmptyException: uploads
How each call behaves:
Files.delete(file)removes the file. It returns nothing; if it returns without an exception, the file is gone.- Deleting it again throws
NoSuchFileException. Usedeletewhen the file must exist — if it's missing, something unexpected happened, and an exception reports that. Files.deleteIfExists(file)returnsfalsewhen there was nothing to delete andtruewhen it deleted the file. Use it for cleanup, where "already gone" is a perfectly good outcome — removing a temporary file, a cache entry or a lock file.- A non-empty folder can't be deleted:
DirectoryNotEmptyException. An empty folder is deleted just like a file.
Other failures throw other IOException subclasses, so you can see why a delete failed:
| Exception | Typical cause |
|---|---|
NoSuchFileException | The path doesn't exist (delete only) |
DirectoryNotEmptyException | The folder still contains entries |
AccessDeniedException | No permission to modify the parent folder, a read-only file on Windows, or a file open in another program on Windows |
FileSystemException | Other OS-level reasons, such as the file being in use |
On Linux and macOS, permission to delete a file depends on write permission on the folder that contains it, not on the file itself. A read-only file in a writable folder can be deleted; a writable file in a read-only folder can't.
Avoid "Check Then Delete"
if (Files.exists(path)) {
Files.delete(path); // can still throw NoSuchFileException
}
Another thread or process can delete the file between the check and the delete, so this code can fail exactly when it seemed safe. Files.deleteIfExists(path) performs the check and the deletion as one operation and expresses the intent directly.
File.delete (java.io)
import java.io.File;
public class D2 {
public static void main(String[] args) {
File missing = new File("never-existed.txt");
System.out.println("delete missing file: " + missing.delete());
File dir = new File("uploads");
System.out.println("delete non-empty dir: " + dir.delete());
}
}
Output (run after the previous example, so uploads still contains photo.jpg):
delete missing file: false
delete non-empty dir: false
Both calls return false, but for completely different reasons — the file didn't exist, and the folder wasn't empty. Nothing tells you which, and a failure caused by permissions would look exactly the same. Code that ignores the return value (file.delete();) can't even tell that anything went wrong. When maintaining older code that uses File, you can get proper exceptions by switching to Files.delete(file.toPath()).
Deleting a Folder and Everything Inside It
Because a folder must be empty before it can be deleted, removing a tree means deleting the deepest entries first and working back up to the root.
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Comparator;
import java.util.stream.Stream;
public class D3 {
static void deleteTreeSimple(Path root) throws IOException {
try (Stream<Path> paths = Files.walk(root)) {
for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(p);
}
}
}
static int deleteTree(Path root) throws IOException {
int[] count = {0};
Files.walkFileTree(root, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
count[0]++;
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null) throw exc;
Files.delete(dir);
count[0]++;
return FileVisitResult.CONTINUE;
}
});
return count[0];
}
static void build(Path root) throws IOException {
Files.createDirectories(root.resolve("2026/10"));
Files.createDirectories(root.resolve("2026/11"));
Files.writeString(root.resolve("2026/10/a.log"), "a");
Files.writeString(root.resolve("2026/11/b.log"), "b");
Files.writeString(root.resolve("2026/11/c.log"), "c");
}
public static void main(String[] args) throws IOException {
Path root = Path.of("build-output");
build(root);
try (Stream<Path> paths = Files.walk(root)) {
paths.sorted(Comparator.reverseOrder()).forEach(System.out::println);
}
deleteTreeSimple(root);
System.out.println("simple delete, exists: " + Files.exists(root));
build(root);
System.out.println("walkFileTree deleted " + deleteTree(root) + " entries, exists: " + Files.exists(root));
}
}
Output:
build-output/2026/11/c.log
build-output/2026/11/b.log
build-output/2026/11
build-output/2026/10/a.log
build-output/2026/10
build-output/2026
build-output
simple delete, exists: false
walkFileTree deleted 7 entries, exists: false
Approach 1: Files.walk sorted in reverse
Files.walk(root)returns a stream of the root and everything below it.- Sorting the paths in reverse order places every path before its parent (
build-output/2026/11/c.logcomes beforebuild-output/2026/11, which comes beforebuild-output/2026). The printed list shows exactly the order in which entries are deleted: contents first, folders after. .toList()collects the paths before deleting. This means all entries are collected in memory, which is fine for ordinary folder sizes.- The stream holds open directory handles, so it's closed with try-with-resources.
This approach is short and easy to read, and it's the one you'll see most often in application code and tests.
Approach 2: Files.walkFileTree with a visitor
Files.walkFileTree traverses the tree and calls methods on a visitor object at each step. SimpleFileVisitor provides default implementations, so you override only what you need:
visitFileis called for each file; it deletes the file.postVisitDirectoryis called after all entries of a folder have been visited — exactly the moment the folder has become empty, so it can be deleted. Theexcparameter contains any error that occurred while listing that folder; rethrowing it stops the deletion rather than trying to delete a folder whose contents couldn't be read.- Returning
FileVisitResult.CONTINUEtells the walk to keep going.
Because the work happens as the walk proceeds, it doesn't need to collect all paths first, and it gives precise control over errors (visitFileFailed can be overridden to skip unreadable files instead of stopping). The anonymous class can't modify a local int, so the counter is kept in a one-element array, a common workaround.
Both approaches do not follow symbolic links by default: a link inside the tree is deleted as a link, and the files it points to elsewhere are left alone. That default is important for safety — following links could delete files far outside the folder you meant to clean.
Deleting a Symbolic Link
A symbolic link is a small file-system entry that points to another path, like a shortcut. Deleting the link removes only the link:
import java.io.IOException;
import java.nio.file.*;
public class D4 {
public static void main(String[] args) throws IOException {
Path target = Files.writeString(Path.of("real-config.yaml"), "port: 8080\n");
Path link = Files.createSymbolicLink(Path.of("current-config.yaml"), target.getFileName());
Files.delete(link);
System.out.println("link exists: " + Files.exists(link, LinkOption.NOFOLLOW_LINKS)
+ ", target exists: " + Files.exists(target));
}
}
Output (on Linux or macOS; creating symbolic links on Windows requires Developer Mode or administrator rights):
link exists: false, target exists: true
Files.exists normally follows links, so it's called with LinkOption.NOFOLLOW_LINKS to ask about the link itself. The target file is untouched. Deployment scripts rely on this behaviour, for example by pointing a current link at the latest release and replacing the link on each deploy.
Deleting Open Files
Operating systems differ on deleting a file that's still open:
- Linux and macOS allow it. The name disappears from the folder immediately, but the data stays on disk until the last program holding it open closes it. This is why disk space sometimes isn't freed after deleting a large log file that a running process is still writing to.
- Windows normally refuses, throwing
FileSystemException("The process cannot access the file because it is being used by another process") orAccessDeniedException.
Close streams before deleting files (try-with-resources makes this automatic) so the same code behaves correctly on every platform.
Practical Example: Cleaning Up Old Log Files
Servers accumulate log files, exports and temporary uploads that must be removed after a retention period, or the disk eventually fills up. This method deletes matching files older than a given age, reports what it did, and keeps going if a single file can't be deleted.
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.FileTime;
import java.time.*;
import java.util.*;
import java.util.stream.Stream;
public class Cleanup {
record Result(List<String> deleted, List<String> kept, long bytesFreed) { }
static Result deleteOlderThan(Path dir, String glob, Duration maxAge, Instant now) throws IOException {
Instant cutoff = now.minus(maxAge);
PathMatcher matcher = dir.getFileSystem().getPathMatcher("glob:" + glob);
List<String> deleted = new ArrayList<>(), kept = new ArrayList<>();
long freed = 0;
try (Stream<Path> files = Files.list(dir)) {
for (Path p : files.sorted().toList()) {
if (!Files.isRegularFile(p) || !matcher.matches(p.getFileName())) continue;
Instant modified = Files.getLastModifiedTime(p).toInstant();
if (modified.isBefore(cutoff)) {
long size = Files.size(p);
try {
if (Files.deleteIfExists(p)) {
deleted.add(p.getFileName().toString());
freed += size;
}
} catch (IOException e) {
System.out.println("could not delete " + p.getFileName() + ": " + e);
}
} else {
kept.add(p.getFileName().toString());
}
}
}
return new Result(deleted, kept, freed);
}
public static void main(String[] args) throws IOException {
Path logs = Files.createDirectories(Path.of("logs"));
Instant now = Instant.parse("2026-11-15T04:00:00Z");
Map<String, Integer> ageInDays = Map.of(
"app-2026-10-01.log", 45, "app-2026-11-01.log", 14, "app-2026-11-14.log", 1, "notes.txt", 60);
for (var entry : ageInDays.entrySet()) {
Path p = Files.writeString(logs.resolve(entry.getKey()), "x".repeat(1000));
Files.setLastModifiedTime(p, FileTime.from(now.minus(Duration.ofDays(entry.getValue()))));
}
Result r = deleteOlderThan(logs, "*.log", Duration.ofDays(7), now);
System.out.println("deleted: " + r.deleted());
System.out.println("kept: " + r.kept());
System.out.println("freed: " + r.bytesFreed() + " bytes");
}
}
Output:
deleted: [app-2026-10-01.log, app-2026-11-01.log]
kept: [app-2026-11-14.log]
freed: 2000 bytes
Step by step:
- Test data with controlled ages.
maincreates four 1,000-byte files and usesFiles.setLastModifiedTimeto make them look 45, 14, 1 and 60 days old relative to a fixed "now". Passingnowas a parameter instead of callingInstant.now()inside the method makes the behaviour testable. - Only matching files are considered. A
PathMatcherwith the glob pattern*.logmatches file names ending in.log.notes.txtis 60 days old but doesn't match, so it's neither deleted nor listed — a cleanup job must never touch files it wasn't designed for.Files.isRegularFilealso skips subfolders. - Age is compared with a cutoff. Files modified before
now - 7 daysare deleted; the one-day-old log is kept. - The size is read before deleting, because it can't be read afterwards. Only successful deletions count toward the freed space.
deleteIfExistsinside its owntry. If another process removed a file in the meantime,deleteIfExistsjust returnsfalse. If one file can't be deleted (permissions, a file locked on Windows), the error is reported and the loop continues with the rest, so one problem doesn't stop the whole cleanup.Files.listlists only the folder's direct entries (not subfolders' contents) and is closed with try-with-resources. Sorting the paths makes the order of the output predictable.
In production, a method like this typically runs on a schedule (a ScheduledExecutorService, a Spring @Scheduled method or a cron job), and logs its result instead of printing it. Before enabling automatic deletion in a new environment, many teams run it in a "dry run" mode that only reports what would be deleted.