Skip to lesson

Copy or delete a whole folder tree safely

Files.delete and Files.copy work on one file or one empty folder. Whole folder trees need a walk, and because a tree delete cannot be undone, the code around it needs a few safety checks that every professional tool has.

Deleting a tree: walk in reverse order

A folder can be deleted only when it is empty, so a tree must be deleted deepest first: files, then their folders, then the folders above them.

Example 1 · Deleting a tree deepest first

DeleteTreeDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.stream.Stream;
public class DeleteTreeDemo {    static String show(Path root, Path p) {        List<String> names = new ArrayList<>();        for (Path n : root.relativize(p)) {            names.add(n.toString());        }        String s = String.join("/", names);        return s.isEmpty() ? "." : s;    }
    static int deleteTree(Path root) throws IOException {        if (Files.notExists(root)) {            return 0;        }        List<Path> all;        try (Stream<Path> s = Files.walk(root)) {            all = s.sorted(Comparator.reverseOrder()).toList();        }        for (Path p : all) {            System.out.println("  delete " + show(root, p));            Files.delete(p);        }        return all.size();    }
    public static void main(String[] args) throws IOException {        Path root = Path.of("old-project");        Files.createDirectories(root.resolve("src/util"));        Files.writeString(root.resolve("notes.txt"), "todo");        Files.writeString(root.resolve("src/main.java"), "class Main {}");        Files.writeString(root.resolve("src/util/helper.java"), "class Helper {}");
        System.out.println("Deleting:");        int n = deleteTree(root);        System.out.println(n + " items deleted, folder exists: " + Files.exists(root));        System.out.println("Second call deletes: " + deleteTree(root));    }}
Output
Deleting:
  delete src/util/helper.java
  delete src/util
  delete src/main.java
  delete src
  delete notes.txt
  delete .
6 items deleted, folder exists: false
Second call deletes: 0

What this code does

  • In reverse order src/util/helper.java comes before src/util, and src before the start folder (.), so every folder is already empty when its turn comes.
  • The paths are collected first, inside try-with-resources, so the walk is closed before anything is deleted. A missing folder simply returns 0.

Files.walk gives the opposite order, parents before children. Sorting its paths with Comparator.reverseOrder() fixes that: a child's path always starts with its parent's path and is longer, so in reverse order every child comes before its parent. Collect the sorted list inside try-with-resources, then delete each path.

walkFileTree with SimpleFileVisitor

Files.walkFileTree(start, visitor) walks a tree and calls your visitor object at each step. A FileVisitor has four methods: preVisitDirectory (before a folder's contents), visitFile (each file), visitFileFailed (a file that could not be read) and postVisitDirectory (after a folder's contents).

Example 2 · Copying a tree with a visitor

CopyTreeDemo.javaJava
import java.io.IOException;import java.nio.file.FileVisitResult;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.SimpleFileVisitor;import java.nio.file.StandardCopyOption;import java.nio.file.attribute.BasicFileAttributes;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.stream.Stream;
public class CopyTreeDemo {    static String show(Path root, Path p) {        List<String> names = new ArrayList<>();        for (Path n : root.relativize(p)) {            names.add(n.toString());        }        String s = String.join("/", names);        return s.isEmpty() ? "." : s;    }
    static void deleteTree(Path root) throws IOException {        try (Stream<Path> s = Files.walk(root)) {            for (Path p : s.sorted(Comparator.reverseOrder()).toList()) {                Files.delete(p);            }        }    }
    static int copyTree(Path source, Path target) throws IOException {        int[] files = {0};        Files.walkFileTree(source, new SimpleFileVisitor<>() {            @Override            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {                Files.createDirectories(target.resolve(source.relativize(dir)));                return FileVisitResult.CONTINUE;            }
            @Override            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {                Files.copy(file, target.resolve(source.relativize(file)), StandardCopyOption.COPY_ATTRIBUTES);                files[0]++;                return FileVisitResult.CONTINUE;            }        });        return files[0];    }
    public static void main(String[] args) throws IOException {        Path project = Path.of("hackathon");        Files.createDirectories(project.resolve("src/ui"));        Files.createDirectories(project.resolve("docs"));        Files.writeString(project.resolve("src/app.java"), "class App {}");        Files.writeString(project.resolve("src/ui/menu.java"), "class Menu {}");        Files.writeString(project.resolve("docs/pitch.txt"), "Team Byte Bandits");
        Path backup = Path.of("hackathon-backup");        System.out.println("Copied " + copyTree(project, backup) + " files");
        boolean same = true;        try (Stream<Path> s = Files.walk(backup)) {            for (Path p : s.sorted(Comparator.comparing(p -> show(backup, p))).toList()) {                System.out.println("  " + show(backup, p));                if (Files.isRegularFile(p)) {                    same &= Files.mismatch(p, project.resolve(backup.relativize(p))) == -1;                }            }        }        System.out.println("All files identical? " + same);
        deleteTree(project);        deleteTree(backup);    }}
Output
Copied 3 files
  .
  docs
  docs/pitch.txt
  src
  src/app.java
  src/ui
  src/ui/menu.java
All files identical? true

What this code does

  • source.relativize(dir) gives the folder's position inside the source, and target.resolve(...) puts it at the same position in the target. preVisitDirectory runs before a folder's files, so the folder always exists in time.
  • The anonymous SimpleFileVisitor overrides only two of the four methods. A local variable used inside it must be effectively final, so the counter is a one-element array.

Example 3 · Visitor control: skip build folders, then delete

VisitorControlDemo.javaJava
import java.io.IOException;import java.nio.file.FileVisitResult;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.SimpleFileVisitor;import java.nio.file.attribute.BasicFileAttributes;import java.util.Set;
public class VisitorControlDemo {    static final Set<String> SKIP = Set.of("build", ".git");
    static long sourceSize(Path root) throws IOException {        long[] total = {0};        Files.walkFileTree(root, new SimpleFileVisitor<>() {            @Override            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {                if (SKIP.contains(dir.getFileName().toString())) {                    System.out.println("  skipping " + dir.getFileName());                    return FileVisitResult.SKIP_SUBTREE;                }                return FileVisitResult.CONTINUE;            }
            @Override            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {                total[0] += attrs.size();                return FileVisitResult.CONTINUE;            }
            @Override            public FileVisitResult visitFileFailed(Path file, IOException e) {                System.out.println("  cannot read " + file.getFileName() + ": " + e.getClass().getSimpleName());                return FileVisitResult.CONTINUE;            }        });        return total[0];    }
    static void deleteWithVisitor(Path root) throws IOException {        Files.walkFileTree(root, new SimpleFileVisitor<>() {            @Override            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {                Files.delete(file);                return FileVisitResult.CONTINUE;            }
            @Override            public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {                if (e != null) {                    throw e;                }                Files.delete(dir);                return FileVisitResult.CONTINUE;            }        });    }
    public static void main(String[] args) throws IOException {        Path root = Path.of("mini-app");        Files.createDirectories(root.resolve("src"));        Files.createDirectories(root.resolve("build"));        Files.writeString(root.resolve("src/app.java"), "x".repeat(120));        Files.writeString(root.resolve("build/app.class"), "y".repeat(900));        Files.writeString(root.resolve("readme.txt"), "z".repeat(30));
        System.out.println("Source size: " + sourceSize(root) + " bytes");        deleteWithVisitor(root);        System.out.println("Deleted, exists: " + Files.exists(root));    }}
Output
  skipping build
Source size: 150 bytes
Deleted, exists: false

What this code does

  • SKIP_SUBTREE from preVisitDirectory keeps the walk out of build, so its 900 bytes are not counted: 120 + 30 = 150. visitFileFailed reports an unreadable file and continues instead of stopping the whole walk.
  • The delete visitor removes files in visitFile and each folder in postVisitDirectory, which runs after the folder's contents are gone. If something inside failed, e is not null and is rethrown.

SimpleFileVisitor gives all four a default, so you override only what you need. Each method returns a FileVisitResult: CONTINUE, SKIP_SUBTREE (do not enter this folder), SKIP_SIBLINGS or TERMINATE. That control is what Files.walk lacks.

The two classic visitors: copying creates each folder in preVisitDirectory and copies each file in visitFile; deleting removes each file in visitFile and each folder in postVisitDirectory, when it is already empty.

Order of execution

Walk order

Files.walkFileTree starts at reports, which holds one folder 2025 with one file jan.csv. Tap the calls in order.

Symbolic links and loops

A symbolic link (symlink) is a small file that points to another path, like a shortcut. A link can point to a folder higher up in the same tree, so a walk that follows links would go round in a loop forever.

Java
// Default: links are listed, never enteredtry (Stream<Path> s = Files.walk(root)) { /* ... */ }
// Follows links; a loop gives FileSystemLoopExceptiontry (Stream<Path> s = Files.walk(root, FileVisitOption.FOLLOW_LINKS)) { /* ... */ }
boolean isLink = Files.isSymbolicLink(p);boolean realFolder = Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS);

By default, Files.walk and walkFileTree do not follow links: a link is reported as an entry, but not entered. That default is also what makes tree deletes safe: deleting the link removes only the link, never the files it points to. Pass FileVisitOption.FOLLOW_LINKS only when you really need the link targets; then Java detects a loop and reports FileSystemLoopException instead of running forever.

On Windows, creating a symbolic link needs administrator rights or Developer Mode. Your code must still expect links, because other programs create them.

Path traversal: normalize and check startsWith a base folder

Path traversal is a bug or attack where a file name such as ../../secret.txt escapes the folder it was meant to stay in. Normalize the path and check it still starts with the base folder.

Path traversal is an attack where a user sends a file name such as ../../secret.properties to reach files outside the folder you meant. uploads.resolve(name) happily follows the .. parts, and an absolute name makes resolve ignore uploads completely.

Example 4 · Blocking path traversal in a download feature

TraversalDemo.javaJava
import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
public class TraversalDemo {    static String show(Path root, Path p) {        List<String> names = new ArrayList<>();        for (Path n : root.relativize(p)) {            names.add(n.toString());        }        String s = String.join("/", names);        return s.isEmpty() ? "." : s;    }
    static Path safeResolve(Path base, String userInput) {        Path root = base.toAbsolutePath().normalize();        Path target = root.resolve(userInput).normalize();        if (!target.startsWith(root)) {            throw new SecurityException("Outside the upload folder: " + userInput);        }        return target;    }
    public static void main(String[] args) {        Path uploads = Path.of("uploads");        Path root = uploads.toAbsolutePath().normalize();        String absolute = Path.of("config", "db.properties").toAbsolutePath().toString();
        List<String> inputs = List.of("notes.txt", "sem1/marks.csv", "sem1/../notes.txt",                "../secret.txt", "sem1/../../secret.txt", absolute);        for (String in : inputs) {            String label = in.equals(absolute) ? "(an absolute path)" : in;            try {                Path t = safeResolve(uploads, in);                System.out.println(label + " -> OK: " + show(root, t));            } catch (SecurityException e) {                System.out.println(label + " -> REJECTED");            }        }
        Path sneaky = root.resolveSibling("uploads-old").resolve("hack.txt");        System.out.println("String startsWith: " + sneaky.toString().startsWith(root.toString()));        System.out.println("Path startsWith:   " + sneaky.startsWith(root));    }}
Output
notes.txt -> OK: notes.txt
sem1/marks.csv -> OK: sem1/marks.csv
sem1/../notes.txt -> OK: notes.txt
../secret.txt -> REJECTED
sem1/../../secret.txt -> REJECTED
(an absolute path) -> REJECTED
String startsWith: true
Path startsWith:   false

What this code does

  • After normalize, sem1/../../secret.txt points one level above uploads, so it no longer starts with the base folder and is rejected. An absolute input makes resolve ignore the base completely, and the same check catches it.
  • The last two lines show why the check uses Path.startsWith: as text, .../uploads-old/hack.txt begins with .../uploads, but as names uploads-old is not uploads.

The fix has three steps: make the base folder absolute and normalized, resolve the user's text against it and normalize the result, then check that the result still starts with the base folder. Reject anything else. Use Path.startsWith, not String.startsWith. Path.startsWith compares whole names, so uploads-old/hack.txt does not start with uploads; the string version says it does.

If links may exist inside the base folder, compare toRealPath() results as well, because a link can point outside.

Confirming before deleting

A tree delete has no undo, so production tools add guard rails before they delete anything. This example puts the main ones in a single method.

Example 5 · A delete with guard rails and a dry run

SafeDeleteDemo.javaJava
import java.io.IOException;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 SafeDeleteDemo {    static void safeDelete(Path allowedBase, Path target, boolean confirmed) throws IOException {        Path base = allowedBase.toAbsolutePath().normalize();        Path t = target.toAbsolutePath().normalize();        if (!t.startsWith(base) || t.equals(base)) {            System.out.println("Refused: not a folder inside " + allowedBase.getFileName());            return;        }        if (Files.notExists(t)) {            System.out.println("Nothing to delete");            return;        }
        List<Path> all;        try (Stream<Path> s = Files.walk(t)) {            all = s.sorted(Comparator.reverseOrder()).toList();        }        long files = 0;        long bytes = 0;        for (Path p : all) {            if (Files.isRegularFile(p)) {                files++;                bytes += Files.size(p);            }        }        System.out.println("Would delete " + files + " files (" + bytes + " bytes) in " + t.getFileName());        if (!confirmed) {            System.out.println("Dry run: nothing deleted");            return;        }        for (Path p : all) {            Files.delete(p);        }        System.out.println("Deleted " + all.size() + " items");    }
    public static void main(String[] args) throws IOException {        Path work = Path.of("workspace");        Path builds = work.resolve("old-builds");        Files.createDirectories(builds.resolve("v1"));        Files.writeString(builds.resolve("v1/app.jar"), "a".repeat(500));        Files.writeString(builds.resolve("build.log"), "b".repeat(40));
        safeDelete(work, builds, false);        safeDelete(work, builds, true);        safeDelete(work, builds, true);        safeDelete(work, work, true);        safeDelete(work, work.resolve(".."), true);        safeDelete(work, Path.of(System.getProperty("user.home")), true);
        Files.delete(work);    }}
Output
Would delete 2 files (540 bytes) in old-builds
Dry run: nothing deleted
Would delete 2 files (540 bytes) in old-builds
Deleted 4 items
Nothing to delete
Refused: not a folder inside workspace
Refused: not a folder inside workspace
Refused: not a folder inside workspace

What this code does

  • The first call only reports what would go. The second, confirmed call deletes the 2 files and 2 folders; the third finds nothing left.
  • The base folder itself, its parent (workspace/..) and the home folder are all refused before any walk starts, because after normalize none of them is strictly inside workspace.
  • Refuse dangerous targets: a drive root, the home folder, the working directory, an empty path, or anything outside an allowed base folder.
  • Do a dry run first: list how many files and bytes would go, and change nothing.
  • Delete only after an explicit confirmation, such as a --yes flag or typing the folder name.
  • Log what was deleted, so a mistake can at least be traced.

Next step

Check your understanding

12 quick questions