Java Delete Files

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 138 of 306

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:

MethodIf the target doesn't existIf deletion failsPackage
Files.delete(path)Throws NoSuchFileExceptionThrows a specific IOExceptionjava.nio.file
Files.deleteIfExists(path)Returns falseThrows a specific IOExceptionjava.nio.file
file.delete()Returns falseReturns 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:

  1. Files.delete(file) removes the file. It returns nothing; if it returns without an exception, the file is gone.
  2. Deleting it again throws NoSuchFileException. Use delete when the file must exist — if it's missing, something unexpected happened, and an exception reports that.
  3. Files.deleteIfExists(file) returns false when there was nothing to delete and true when 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.
  4. 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:

ExceptionTypical cause
NoSuchFileExceptionThe path doesn't exist (delete only)
DirectoryNotEmptyExceptionThe folder still contains entries
AccessDeniedExceptionNo permission to modify the parent folder, a read-only file on Windows, or a file open in another program on Windows
FileSystemExceptionOther 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.log comes before build-output/2026/11, which comes before build-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:

  • visitFile is called for each file; it deletes the file.
  • postVisitDirectory is called after all entries of a folder have been visited — exactly the moment the folder has become empty, so it can be deleted. The exc parameter 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.CONTINUE tells 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.

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") or AccessDeniedException.

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:

  1. Test data with controlled ages. main creates four 1,000-byte files and uses Files.setLastModifiedTime to make them look 45, 14, 1 and 60 days old relative to a fixed "now". Passing now as a parameter instead of calling Instant.now() inside the method makes the behaviour testable.
  2. Only matching files are considered. A PathMatcher with the glob pattern *.log matches file names ending in .log. notes.txt is 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.isRegularFile also skips subfolders.
  3. Age is compared with a cutoff. Files modified before now - 7 days are deleted; the one-day-old log is kept.
  4. The size is read before deleting, because it can't be read afterwards. Only successful deletions count toward the freed space.
  5. deleteIfExists inside its own try. If another process removed a file in the meantime, deleteIfExists just returns false. 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.
  6. Files.list lists 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Delete Files and get answers drawn from it.

Signed-in readers only.