Skip to lesson

Paths and files: common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most file system bugs come from four habits: typing separators and drive letters into code, walking folders carelessly, matching file types with loose string checks, and deleting without guard rails. Each has a short, reliable fix.

Mistake 1: Windows-only path code

Code like "data\\" + roll + ".txt" or "C:\\Users\\Asha\\marks.csv" works on the laptop it was written on. On Linux the backslash is an ordinary character, so the whole string becomes one strange file name in the working directory, and the drive letter means nothing.

Example 1 · Mistake: a hand-built Windows path

WindowsOnlyDemo.javaJava
import java.nio.file.Path;
public class WindowsOnlyDemo {    static Path buggyReport(String roll) {        return Path.of("data" + "\\" + roll + ".txt");    }
    static Path fixedReport(String roll) {        return Path.of("data").resolve(roll + ".txt");    }
    public static void main(String[] args) {        Path bad = buggyReport("21");        Path good = fixedReport("21");        System.out.println("buggy: names=" + bad.getNameCount() + ", file=" + bad.getFileName()                + ", parent=" + bad.getParent());        System.out.println("fixed: names=" + good.getNameCount() + ", file=" + good.getFileName()                + ", parent=" + good.getParent());    }}
Sample output (Linux, where the bug shows; on Windows both lines look like the fixed one)
buggy: names=1, file=data\21.txt, parent=null
fixed: names=2, file=21.txt, parent=data

What this code does

  • On Linux, \ is just a character, so data\21.txt is one file name with no folder. The program would create or look for that odd file in the working directory and never use the data folder.
  • Path.of("data").resolve(roll + ".txt") gives two names on every system: the folder data and the file 21.txt.

The fix is always the same: build paths from parts with Path.of(a, b, c) or resolve, start user files from user.home, and take other locations from an argument or a settings file. Then test once on a Linux machine, or at least read the code for \\, C: and / inside strings.

Mistake 2: A folder size that counts wrong or leaks

Files.size(folder) does not add up the files inside; it returns a small system-specific number for the folder entry itself. A folder size calculator must walk the tree and add Files.size of every regular file.

Example 2 · Folder size calculator

FolderSizeDemo.javaJava
import java.io.IOException;import java.io.UncheckedIOException;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.Comparator;import java.util.stream.Stream;
public class FolderSizeDemo {    static long folderSize(Path root) throws IOException {        try (Stream<Path> s = Files.find(root, Integer.MAX_VALUE, (p, a) -> a.isRegularFile())) {            return s.mapToLong(p -> {                try {                    return Files.size(p);                } catch (IOException e) {                    throw new UncheckedIOException(e);                }            }).sum();        }    }
    static long folderSizeWithVisitor(Path root) throws IOException {        long[] total = {0};        Files.walkFileTree(root, new SimpleFileVisitor<>() {            @Override            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {                if (attrs.isRegularFile()) {                    total[0] += attrs.size();                }                return FileVisitResult.CONTINUE;            }        });        return total[0];    }    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);            }        }    }
    public static void main(String[] args) throws IOException {        Path root = Path.of("semester");        Files.createDirectories(root.resolve("notes"));        Files.writeString(root.resolve("notes/java.txt"), "a".repeat(1200));        Files.writeString(root.resolve("notes/dbms.txt"), "b".repeat(800));        Files.writeString(root.resolve("marks.csv"), "c".repeat(48));
        System.out.println("Folder size by walking: " + folderSize(root) + " bytes");        System.out.println("Same with a visitor:    " + folderSizeWithVisitor(root) + " bytes");
        deleteTree(root);    }}
Output
Folder size by walking: 2048 bytes
Same with a visitor:    2048 bytes

What this code does

  • Only regular files are added: 1200 + 800 + 48 = 2048. Files.size inside a lambda must be wrapped, because a lambda for mapToLong cannot throw a checked IOException.
  • The visitor version reads attrs.size() from the attributes the walk already has, so there is no extra disk call and no wrapping, and nothing to close. The find stream is closed by try-with-resources.

Two more slips are common here: forgetting try-with-resources around Files.walk, which leaks a directory handle on every call, and calling Files.size inside a stream lambda, which does not compile because it throws a checked IOException. Use a plain loop, or a walkFileTree visitor that reads attrs.size().

Mistake 3: Loose extension checks

p.toString().endsWith("csv") matches far too much: a folder named old-csv, a file notes.mycsv, any path whose folder ends in csv. It also misses MARKS.CSV because the case differs.

Example 3 · Find files by extension, the careful way

FindByExtensionDemo.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 FindByExtensionDemo {    static String show(Path root, Path p) {        List<String> names = new ArrayList<>();        for (Path n : root.relativize(p)) {            names.add(n.toString());        }        return String.join("/", names);    }
    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 List<String> loose(Path root, String ext) throws IOException {        try (Stream<Path> s = Files.walk(root)) {            return s.filter(p -> p.toString().endsWith(ext)).map(p -> show(root, p)).sorted().toList();        }    }
    static List<String> careful(Path root, String ext) throws IOException {        String suffix = "." + ext.toLowerCase();        try (Stream<Path> s = Files.walk(root)) {            return s.filter(Files::isRegularFile)                    .filter(p -> p.getFileName().toString().toLowerCase().endsWith(suffix))                    .map(p -> show(root, p))                    .sorted()                    .toList();        }    }
    public static void main(String[] args) throws IOException {        Path root = Path.of("drive");        Files.createDirectories(root.resolve("old-csv"));        Files.createDirectories(root.resolve("results"));        for (String f : List.of("results/sem1.csv", "results/SEM2.CSV", "results/notes.mycsv",                "old-csv/readme.txt", "budget.xlsx")) {            Files.writeString(root.resolve(f), "data");        }
        System.out.println("Loose:   " + loose(root, "csv"));        System.out.println("Careful: " + careful(root, "csv"));
        deleteTree(root);    }}
Output
Loose:   [old-csv, results/notes.mycsv, results/sem1.csv]
Careful: [results/SEM2.CSV, results/sem1.csv]

What this code does

  • The loose check matched a folder (old-csv) and notes.mycsv, and missed SEM2.CSV because of its case.
  • The careful check keeps regular files only, looks at the file name, compares in lower case and includes the dot. (The sort puts upper-case letters first, which is why SEM2.CSV is listed before sem1.csv.)

A correct find by extension checks three things: the path is a regular file, the check uses the file name, not the whole path, and both sides are lower case with the dot included: name.toLowerCase().endsWith(".csv").

Mistake 4: Deleting without checks

A tree delete with no checks can wipe the wrong folder: a user types .., an argument is empty, or a path from a request contains ../../. Deleting folders before their contents fails halfway with DirectoryNotEmptyException and leaves a half-deleted tree.

Example 4 · Safe delete with checks

SafeDeleteToolDemo.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 SafeDeleteToolDemo {    static String deleteInside(Path base, String input, boolean confirmed) throws IOException {        if (input.isBlank()) {            return "refused: empty name";        }        Path root = base.toAbsolutePath().normalize();        Path target = root.resolve(input).normalize();        if (!target.startsWith(root) || target.equals(root)) {            return "refused: outside " + base.getFileName();        }        if (Files.notExists(target)) {            return "nothing there";        }        List<Path> all;        try (Stream<Path> s = Files.walk(target)) {            all = s.sorted(Comparator.reverseOrder()).toList();        }        if (!confirmed) {            return "dry run: would delete " + all.size() + " items";        }        for (Path p : all) {            Files.delete(p);        }        return "deleted " + all.size() + " items";    }
    public static void main(String[] args) throws IOException {        Path base = Path.of("college-drive");        Files.createDirectories(base.resolve("sem1/assignments"));        Files.writeString(base.resolve("sem1/assignments/a1.txt"), "done");        Files.writeString(base.resolve("sem1/timetable.pdf"), "mon-fri");
        System.out.println("sem1 (dry run)   -> " + deleteInside(base, "sem1", false));        System.out.println("..               -> " + deleteInside(base, "..", true));        System.out.println("sem1/../..       -> " + deleteInside(base, "sem1/../..", true));        System.out.println("(empty)          -> " + deleteInside(base, "  ", true));        System.out.println("sem1             -> " + deleteInside(base, "sem1", true));        System.out.println("sem1 again       -> " + deleteInside(base, "sem1", true));
        Files.delete(base);    }}
Output
sem1 (dry run)   -> dry run: would delete 4 items
..               -> refused: outside college-drive
sem1/../..       -> refused: outside college-drive
(empty)          -> refused: empty name
sem1             -> deleted 4 items
sem1 again       -> nothing there

What this code does

  • Every request is checked before any disk work: blank names, .. and anything that leaves the base after normalize are refused, and so is the base folder itself.
  • Only a confirmed request inside the base deletes, deepest first: a1.txt, assignments, timetable.pdf, then sem1.

A safe delete resolves the input against an allowed base, normalizes it, refuses anything that is not strictly inside the base, does a dry run, and only then deletes deepest first.

Finish up

Mark complete & continue

Next: Read a small text file