Java Programs›File Handling›Delete a Directory Recursively

Delete a Directory Recursively in Java

intermediate·  File Handling  ·  File I/O

Problem

A folder can only be deleted once it's empty, so removing a whole tree means deleting its files and subfolders from the bottom up.

Create a nested build-output folder with files in it, then delete the entire folder.

Input
build-output/ with nested folders and files
Output
folder no longer exists

Java Program

Java
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; import java.util.stream.Stream; public class DeleteDirectoryRecursively { public static void main(String[] args) throws IOException { Path root = Paths.get("build-output"); Files.createDirectories(root.resolve("classes/com/demo")); Files.writeString(root.resolve("classes/com/demo/App.class"), "bytes"); Files.writeString(root.resolve("report.txt"), "ok"); long count; try (Stream<Path> all = Files.walk(root)) { count = all.count(); } System.out.println("Entries before delete: " + count); try (Stream<Path> all = Files.walk(root)) { all.sorted(Comparator.reverseOrder()) // deepest paths first, so folders are empty when deleted .forEach(p -> { try { Files.delete(p); } catch (IOException e) { throw new RuntimeException(e); } }); } System.out.println("Folder exists after delete: " + Files.exists(root)); } }

Output

Entries before delete: 6 Folder exists after delete: false

Core Logic

Sorting the walked paths in reverse order puts every file and subfolder before its parent, so each folder is already empty when its turn comes.

How It Works
  1. 1The program builds a sample tree with nested folders and two files.
  2. 2Files.walk(root) lists every path in the tree, including the root.
  3. 3sorted(Comparator.reverseOrder()) puts longer, deeper paths first.
  4. 4Each path is deleted; Files.delete throws if anything goes wrong.
build-output/classes/com/demo/App.class is deleted before build-output/classes/com/demo, and so on up to the root.
💡

Key Point: Deleting the root first fails with DirectoryNotEmptyException — the order is the whole trick.

Key Concepts

Files.walk()Comparator.reverseOrder()Files.delete()

Approach 2: Using walkFileTree

Java
import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; public class DeleteDirectoryVisitor { public static void main(String[] args) throws IOException { Path root = Paths.get("tmp-cache"); Files.createDirectories(root.resolve("a/b")); Files.writeString(root.resolve("a/b/data.txt"), "x"); Files.writeString(root.resolve("a/info.txt"), "y"); final int[] deleted = {0}; Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); // files first... deleted[0]++; return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); // ...then each folder once it's empty deleted[0]++; return FileVisitResult.CONTINUE; } }); System.out.println("Deleted entries: " + deleted[0]); System.out.println("Exists now: " + Files.exists(root)); } }

Output

Deleted entries: 5 Exists now: false

Core Logic

A FileVisitor gets a callback after each folder's contents have been visited — exactly when that folder can be deleted.

How It Works
  1. 1visitFile deletes each file as it's found.
  2. 2postVisitDirectory deletes a folder after all its contents are gone.
  3. 3A counter records how many entries were deleted.
Two files and three folders are deleted, five entries in total.
💡

Key Point: The visitor approach scales to huge trees because it doesn't build a full list of paths first.

Key Concepts

Files.walkFileTree()SimpleFileVisitorpostVisitDirectory()

Interview Questions

What's the danger of recursive delete code?

A wrong path, such as an empty string or a user's home folder, deletes far more than intended. Validate the path and never follow symbolic links blindly.

Does Files.walk follow symbolic links?

Not by default, which is the safe choice for deletion: the link itself is deleted, not the folder it points to.

Learn the Concept

Related Programs