Sub topic 2
Combining and cleaning paths
This chapter assumes you can create a Path with Path.of and know what a relative path and an absolute path are. It builds on that to cover three jobs: joining paths, removing noise from them, and computing the route from one location to another. All of these are pure operations on names. None of them checks that a file exists.
Paths are values, not files
A Path is an immutable sequence of name elements, with an optional root. Every method in this chapter returns a new Path and leaves the original unchanged. The methods work on the path's text structure only, so you can build and compare paths for files that do not exist yet.
The exceptions are toRealPath() and Files methods such as Files.exists. These ask the operating system, and they are covered later in the tutorial.
The outputs in this chapter use Unix separators (/). On Windows the separator is \, but the logic is identical.
Combining paths with resolve
resolve appends one path to another. Use it instead of string concatenation, because it handles separators for you.
import java.nio.file.Path;
public class ResolveDemo {
public static void main(String[] args) {
Path base = Path.of("data", "reports");
System.out.println(base.resolve("2026/q1.txt"));
System.out.println(base.resolve("/etc/hosts"));
System.out.println(base.resolve(""));
System.out.println(base.resolveSibling("archive"));
}
}On Unix this prints:
data/reports/2026/q1.txt
/etc/hosts
data/reports
data/archiveThree behaviors matter here:
- The argument may contain several elements, such as
"2026/q1.txt".Path.ofalso accepts several string arguments, which it joins with the separator. - If the argument is absolute,
resolvereturns the argument and discards the base. - If the argument is empty,
resolvereturns the base.
resolveSibling replaces the last element of the base. It resolves the argument against the base's parent. It is handy for deriving report.bak from report.txt in the same directory.
The absolute-argument rule is a common source of bugs and security problems. If the second part comes from user input, base.resolve(userInput) can escape base entirely. The next section shows the full defense.
Cleaning paths with normalize
Paths often contain . (the current directory) and .. (the parent directory). normalize removes redundant ones without touching the file system.
import java.nio.file.Path;
public class NormalizeDemo {
public static void main(String[] args) {
System.out.println(Path.of("data/../data/./notes.txt").normalize());
System.out.println(Path.of("a/b/../../..").normalize());
System.out.println(Path.of("/../a").normalize());
System.out.println("[" + Path.of("a/..").normalize() + "]");
}
}The output is:
data/notes.txt
..
/a
[]The rules are:
- A
.element is dropped. - A
..element cancels the name element before it. - A
..that has nothing to cancel is kept in a relative path, as in the second line. - A
..directly after the root is dropped, because the root has no parent. That is why/../abecomes/a. - A path that cancels down to nothing becomes the empty path, which prints as an empty string.
Absolute paths
toAbsolutePath() resolves a relative path against the current working directory. It does not normalize, and it does not check that the file exists.
import java.nio.file.Path;
public class AbsoluteDemo {
public static void main(String[] args) {
Path p = Path.of("src/../notes.txt");
Path abs = p.toAbsolutePath();
System.out.println(abs.isAbsolute());
System.out.println(abs.normalize());
}
}If the working directory is /home/ana/project, the last line prints /home/ana/project/notes.txt. Call toAbsolutePath() first and normalize() second. Normalizing a relative path first can leave leading .. elements that then resolve against the working directory.
Computing the route between two paths with relativize
relativize answers the question: what relative path leads from this location to that one?
import java.nio.file.Path;
public class RelativizeDemo {
public static void main(String[] args) {
Path from = Path.of("/home/ana/project");
Path to = Path.of("/home/ana/docs/a.txt");
Path route = from.relativize(to);
System.out.println(route);
System.out.println(from.resolve(route).normalize());
}
}This prints:
../docs/a.txt
/home/ana/docs/a.txtrelativize and resolve are inverses, as long as you normalize after resolving. The .. that relativize produces stays in the result until you call normalize.
Two gotchas apply:
- Both paths must be the same kind. Mixing an absolute and a relative path throws
IllegalArgumentException. On Windows, paths on different drives, such asC:\aandD:\b, also fail. relativizedoes not clean its inputs. If either path contains.or.., the result can be surprising. Normalize both paths first.
Typical uses include storing paths relative to a project root in a config file, and showing short names in output when you walk a directory tree.
Guarding against path escape
Combining resolve, normalize, and startsWith gives a standard check for untrusted names:
import java.nio.file.Path;
public class SafeResolve {
static Path resolveInside(Path root, String untrusted) {
Path base = root.toAbsolutePath().normalize();
Path candidate = base.resolve(untrusted).normalize();
if (!candidate.startsWith(base)) {
throw new IllegalArgumentException("Path escapes root: " + untrusted);
}
return candidate;
}
public static void main(String[] args) {
Path root = Path.of("uploads");
System.out.println(resolveInside(root, "photos/cat.png"));
try {
resolveInside(root, "../secrets.txt");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}Absolute inputs like /etc/passwd are rejected too, because resolve returns them unchanged and they fail the startsWith test. This check does not follow symbolic links. If links inside the root may point outside it, compare toRealPath() results instead.
Taking paths apart
The reverse of combining is inspecting. These methods also work on names only.
| Method | Result for `/home/ana/notes.txt` |
|---|---|
| `getRoot()` | `/` |
| `getParent()` | `/home/ana` |
| `getFileName()` | `notes.txt` |
| `getNameCount()` | `3` |
| `getName(1)` | `ana` |
| `subpath(0, 2)` | `home/ana` |
Some of these can return null. getParent() returns null for a single-element relative path such as notes.txt. getRoot() returns null for any relative path. getFileName() returns null for a bare root. Check for null before calling methods on the result.
getFileName() returns a Path, not a String. Call toString() when you need text, for example to check an extension.
Comparing paths
startsWith and endsWith compare whole name elements, not characters:
import java.nio.file.Path;
public class CompareDemo {
public static void main(String[] args) {
Path p = Path.of("data/notes.txt");
System.out.println(p.startsWith("data"));
System.out.println(p.startsWith("da"));
System.out.println(p.endsWith("notes.txt"));
System.out.println(Path.of("a/b").equals(Path.of("a/./b")));
System.out.println(Path.of("a/b").equals(Path.of("a/./b").normalize()));
}
}The output is true, false, true, false, true. equals compares the path text, so two spellings of the same location are different until you normalize them. On Windows, equals ignores case, but on Linux it does not. To test whether two paths point at the same existing file, use Files.isSameFile, which asks the file system.
Common mistakes
- Concatenating strings with
"/"instead of usingresolve. This breaks on Windows and doubles separators. - Forgetting that
resolvewith an absolute argument discards the base. - Assuming
normalizechecks the file system, or that it is safe across symbolic links. - Calling
relativizeon one absolute and one relative path. - Calling
getParent().resolve(...)on a bare file name, wheregetParent()isnull.
Exercise
Given root = Path.of("/srv/app") and name = "../app2/data.txt", what does root.resolve(name).normalize() return, and does it pass the check candidate.startsWith(root)? Explain what that means for the guard in resolveInside.
Show answer
It returns /srv/app2/data.txt. The path elements of root are "srv" and "app", while the candidate's first two elements are "srv" and "app2". startsWith compares whole elements, so "app2" does not match "app" and the check is false. The guard correctly rejects the name. A plain string comparison on toString() would wrongly accept it, because "/srv/app2/data.txt" starts with the characters "/srv/app".
Exercise
What does Path.of("/a/b").relativize(Path.of("/a/c/d")) return, and what must you do to turn the result back into /a/c/d?
Show answer
It returns ../c/d. Call Path.of("/a/b").resolve(result).normalize(). Without normalize, the result would be /a/b/../c/d.