Path and directories

A Path is a name of a file or a folder, and it is a value: the program builds it, compares it and asks it questions, and none of that touches the disk. Files is what touches the disk, and it takes a Path. The two lessons before this one used both; this one is about the path itself.

The parts of a path

A path is a root, a list of names and a file name. The program asks one absolute path for each of them:

import java.nio.file.Path; public class Parts { public static void main(String[] args) { Path path = Path.of("/home/ada/docs/report.txt"); System.out.println("name: " + path.getFileName()); System.out.println("parent: " + path.getParent()); System.out.println("count: " + path.getNameCount()); System.out.println("first: " + path.getName(0)); System.out.println("subpath: " + path.subpath(1, 3)); System.out.println("root: " + path.getRoot()); System.out.println("absolute: " + path.isAbsolute()); System.out.println("ends with .txt: " + path.getFileName().toString().endsWith(".txt")); System.out.println("relative: " + Path.of("docs/report.txt").isAbsolute()); } }

javac -Xlint:all Parts.java
java Parts

name: report.txt
parent: /home/ada/docs
count: 4
first: home
subpath: ada/docs
root: /
absolute: true
ends with .txt: true
relative: false

The count is four because the root does not count as a name: home, ada, docs and report.txt. subpath(1, 3) takes the names from index one up to but not including three, which is the same rule as subList of lesson 070 and String.substring. The last line is a relative path, and isAbsolute is how a program tells the two apart before it resolves one.

resolve and resolveSibling

resolve adds a name to a folder, and it has one surprise: an absolute argument replaces the whole path instead of being appended. resolveSibling replaces the last name of the path:

import java.nio.file.Path; public class Resolve { public static void main(String[] args) { Path base = Path.of("/data/site"); System.out.println(base.resolve("index.php")); System.out.println(base.resolve(Path.of("img/logo.png"))); System.out.println(base.resolve("/etc/passwd")); System.out.println(base.resolveSibling("backup")); Path a = Path.of("/data/site/img/logo.png"); Path b = Path.of("/data/site/index.php"); System.out.println("relative: " + b.relativize(a)); Path messy = Path.of("/data/site/../site/./img/logo.png"); System.out.println("messy: " + messy); System.out.println("normal: " + messy.normalize()); System.out.println("equal: " + messy.normalize().equals(a)); System.out.println("starts: " + a.startsWith("/data")); } }

javac -Xlint:all Resolve.java
java Resolve

/data/site/index.php
/data/site/img/logo.png
/etc/passwd
/data/backup
relative: ../img/logo.png
messy: /data/site/../site/./img/logo.png
normal: /data/site/img/logo.png
equal: true
starts: true

The third line is the one to remember: a path built from user input must never be resolved against a base folder without a check, because an absolute argument or a .. takes it out of the folder. The normal form is the same path as the absolute one, which the equals line proves, and a check that a resolved path still startsWith its base is the standard defence.

relativize and normalize

relativize is the inverse of resolve: it answers the path that gets from one place to another, which is ../img/logo.png for a file in a subfolder of the same base. normalize removes the . and .. segments without touching the disk, so a path that arrives in a mess can be compared with a clean one.

Both are pure operations on strings: neither asks the file system whether the file exists, and neither follows a symbolic link. The method that asks whether a file exists is Files.exists, and one that resolves a link is toRealPath, which throws when the file is missing.

Walking a folder

Files.walk answers a stream of every path under a folder, the folder itself first, and Files.list answers one level. The program builds a small tree in a temporary folder and asks it three questions:

import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class Tree { public static void main(String[] args) throws IOException { Path root = Files.createTempDirectory("tree"); Files.createDirectories(root.resolve("src/main")); Files.createDirectories(root.resolve("docs")); Files.writeString(root.resolve("src/main/App.java"), "class App {}", StandardCharsets.UTF_8); Files.writeString(root.resolve("docs/readme.md"), "# readme", StandardCharsets.UTF_8); List<String> names; try (var walk = Files.walk(root)) { names = walk.map(path -> root.relativize(path).toString()) .sorted() .collect(Collectors.toList()); } System.out.println(names); try (var walk = Files.walk(root, 2)) { System.out.println("depth 2: " + walk.count()); } try (var list = Files.list(root)) { System.out.println("top level: " + list.map(p -> p.getFileName().toString()).sorted().collect(Collectors.toList())); } try (var walk = Files.walk(root)) { System.out.println("java files: " + walk.filter(p -> p.toString().endsWith(".java")).count()); } try (var walk = Files.walk(root)) { walk.sorted(Comparator.reverseOrder()).forEach(p -> { try { Files.delete(p); } catch (IOException e) { throw new RuntimeException(e); } }); } System.out.println("gone: " + !Files.exists(root)); } }

javac -Xlint:all Tree.java
java Tree

[, docs, docs/readme.md, src, src/main, src/main/App.java]
depth 2: 5
top level: [docs, src]
java files: 1
gone: true

The first element of the list is the empty string, because the relative path from the root to itself has no names. The depth of 2 counts the root, the two folders and the two files that are one level down, and the walk is a stream that must be closed, as the file stream of lesson 105 was.

A listing and a filter

A listing is a walk of depth one and a filter is the predicate of a pipeline. The two together are a program that finds a file by name under a folder: Files.find takes a matcher with the path and its attributes and is the shortcut when the test needs the size or the time.

The order of a walk is not specified, so a program that prints a folder sorts the result itself, as the program above does with sorted. A folder with a very large tree should be walked with FileVisitor instead of a stream, because that reports the permission errors of a subfolder and a stream throws at the first one; the stream is the right tool for a tree the program can read.

Exercises

  1. Print the name, the parent and the extension of a path given as a constant.
  2. Resolve a name from an absolute path, then a name with a .. in it, and normalize the result.
  3. Count the files with the extension .md in a folder you create with three of them.
  4. Print the paths of a tree with their depth, using the count of names of the relativized path.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Path.of do?

    Answer

    Builds a path value without touching the disk

    A Path is a name, and Files is the class that reads and writes.

  2. What does base.resolve("/etc/passwd") answer?

    Answer

    The absolute path itself, because an absolute argument replaces the base

    This is the rule that makes a resolved user path dangerous without a check.

  3. What does normalize remove?

    Answer

    The . and .. segments of the path

    It is a string operation on the segments and does not ask the disk.

  4. What does this program print? import java.nio.file.Path; public class Q1 { public static void main(String[] args) { Path p = Path.of("docs/2026/report.txt"); System.out.println(p.getFileName()); System.out.println(p.getNameCount()); System.out.println(p.getParent()); } }

    Answer

    report.txt / 3 / docs/2026

    Three names, a file name and a parent of the two folders above it.

  5. What is the difference between Files.list and Files.walk?

    Answer

    list answers one level and walk the whole tree

    The depth argument of walk says how far down it goes, and list is one level.

  6. Why must a stream from Files.walk be closed?

    Answer

    It holds a directory handle

    The walk reads the folders as the stream is consumed, so the handle is released by close.

  7. What does a.relativize(b) answer?

    Answer

    The path that leads from a to b

    It is the inverse of resolve, which is why ../ appears when b is elsewhere.

  8. What does this program print? import java.nio.file.Path; public class Q2 { public static void main(String[] args) { Path base = Path.of("/a/b"); System.out.println(base.resolve("c.txt")); System.out.println(base.resolveSibling("d")); } }

    Answer

    /a/b/c.txt / /a/d

    resolve appends under the base and resolveSibling replaces the last name.

  9. What does this program print? import java.nio.file.Path; public class Q3 { public static void main(String[] args) { Path p = Path.of("/data/./site/../site/x"); System.out.println(p.normalize()); System.out.println(p.getNameCount()); } }

    Answer

    /data/site/x / 6

    The normalize removes the . and the .. and the count is of the six names before it.

  10. Why is the unsafe path resolved from user input a security problem?

    Answer

    An absolute path or .. reaches a file outside the intended folder

    The check that the result still starts with the base folder is the standard defence.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev

Banner image