Java Path Methods: normalize, resolve, relativize and Files Basics (OCP 21)
Working with NIO.2 paths for the OCP 21 exam: immutability, getName, getNameCount and subpath, getFileName, getParent and getRoot, resolve, relativize, normalize, toRealPath and symbolic links, NIO.2 option enums, IOException rules and createDirectory versus createDirectories.
kvi5hnuCode Sprout team member8 min readOn this page
Article 84 showed how to get a Path. This article covers the Path methods that take paths apart and build new ones, the option enums that many NIO.2 methods accept, and how to create directories. The exam asks a lot about the exact output of these methods, so the examples here are precise.
Ground rules for NIO.2
Path objects are immutable
Like String, a Path never changes. Methods such as resolve() and normalize() return a new Path:
Path trail = Path.of("trails");
trail.resolve("north"); // result ignored
System.out.println(trail); // trails
Because they return new paths, these methods chain nicely: Path.of("/a/../b").getParent().normalize().toAbsolutePath().
Most Path methods ignore the disk
Almost every Path method works only on the text of the path. They don't check whether anything exists, and they treat . and .. as ordinary names unless they're specifically designed to handle them. toRealPath() is the exception, and it's covered below.
Which methods throw IOException
Files methods that access or change the file system declare the checked IOException. Common reasons are a missing file, a file that already exists, missing permissions or a lost connection. As a rule of thumb, if an NIO.2 method declares IOException, it usually needs the path to exist. Test methods such as Files.exists() don't throw: if exists() threw for a missing file, it could never return false.
Close NIO.2 streams
Files.list(), and Files.walk(), Files.find() and Files.lines() (article 91), return streams that hold an open file-system resource. A stream's terminal operation doesn't close it. Use try-with-resources. The streams from Chapter 10 had no such resource and didn't need closing. Exam questions sometimes skip the try to keep code short, but your code shouldn't.
Optional parameters
Many NIO.2 methods end with a varargs parameter of option values:
| Enum | Implements | Values |
|---|---|---|
LinkOption | CopyOption, OpenOption | NOFOLLOW_LINKS: work on the link itself, not its target |
StandardCopyOption | CopyOption | ATOMIC_MOVE, COPY_ATTRIBUTES, REPLACE_EXISTING |
StandardOpenOption | OpenOption | READ, WRITE, APPEND (write at the end), CREATE (create if missing), CREATE_NEW (create, failing if it exists), TRUNCATE_EXISTING (empty an existing file opened for writing), and more |
FileVisitOption | (none) | FOLLOW_LINKS: let walk/find follow symbolic links |
Because LinkOption implements CopyOption, a method such as Files.move(source, target, CopyOption... options) accepts both LinkOption.NOFOLLOW_LINKS and StandardCopyOption.ATOMIC_MOVE in the same call.
boolean present = Files.exists(link); // checks the link's TARGET
boolean linkItself = Files.exists(link, LinkOption.NOFOLLOW_LINKS); // checks the link file
For a link whose target is missing, the first call returns false and the second returns true.
Viewing a path: toString, getNameCount, getName, subpath

toString()returns the whole path. It's the onlyPathmethod covered here that returns aString. The others returnPathobjects.getNameCount()returns the number of names. The root isn't a name:/parks/alpine/lakes/blue.maphas 4 names, andPath.of("/")has 0.getName(int index)returns one name as aPath, counting from 0. A bad index throwsIllegalArgumentException, soPath.of("/").getName(0)throws.subpath(int begin, int end)returns namesbegin(inclusive) toend(exclusive), likeString.substring. The result never includes the root, so it's always relative. An end beyondgetNameCount(), orbegin == end, which would make an empty path, throwsIllegalArgumentException.
Path map = Path.of("/parks/alpine/lakes/blue.map");
map.getName(0); // parks
map.subpath(0, 2); // parks/alpine
map.subpath(1, 4); // alpine/lakes/blue.map
map.subpath(2, 2); // IllegalArgumentException
Parts of a path: getFileName, getParent, getRoot
| Method | Returns | null when |
|---|---|---|
getFileName() | the last name | the path is just a root, like / |
getParent() | everything except the last name | there's nothing before the last name: a root, or a single-name relative path |
getRoot() | the root, / on Unix | the path is relative |
Walking up with getParent() until null shows that path symbols are treated as plain names:
/parks/alpine/hut.txt parents: /parks/alpine -> /parks -> /
./alpine/../hut.txt parents: ./alpine/.. -> ./alpine -> .
camp parents: none (getParent() is null, getRoot() is null)
A relative path never "climbs" above its first name. getParent() doesn't look at the working directory.
Joining paths: resolve()
resolve(Path other) and resolve(String other) append the argument to the path they're called on:
Path base = Path.of("/parks/../alpine");
base.resolve("lakes"); // /parks/../alpine/lakes (no cleanup of ..)
base.resolve("/maps/x"); // /maps/x (absolute argument wins)
Think concatenation, with one rule: if the argument is absolute, it's returned unchanged. You can't join two absolute paths. resolveSibling("red.map") replaces the last name instead: lakes/blue.map becomes lakes/red.map.
The way from one path to another: relativize()
a.relativize(b) returns the relative path that leads from a to b, so that a.resolve(a.relativize(b)) gets you to b:
Path.of("camp.txt").relativize(Path.of("alpine/lakes/blue.map")); // ../alpine/lakes/blue.map
Path.of("alpine/lakes/blue.map").relativize(Path.of("camp.txt")); // ../../../camp.txt
Path.of("/parks/alpine").relativize(Path.of("/parks/coast/bay/dock.txt")); // ../coast/bay/dock.txt
- Treat the starting path as a location, including a final file name, and count one
..for each name you climb out of. Fromalpine/lakes/blue.map, it's three levels up to the starting directory. - Two relative paths are assumed to start in the same directory. Two absolute paths work wherever the program runs.
- Mixing an absolute and a relative path throws
IllegalArgumentException. On Windows, two absolute paths on different drives (C:andD:) also throw it.
Cleaning up: normalize()
normalize() removes the redundant . and .. elements:
Path.of("./alpine/../hut.txt").normalize(); // hut.txt
Path.of("/parks/../alpine/lakes").normalize(); // /alpine/lakes
Path.of("lakes/./blue/../red.map").normalize(); // lakes/red.map
Path.of("../../camp.txt").normalize(); // ../../camp.txt (nothing to remove)
Leading .. names in a relative path can't be removed, because there's nothing to cancel them against. normalize() is mainly useful for comparing paths. equals() compares the path text, so /parks/../camp.txt and /camp.txt aren't equal until both are normalized.
Comparing names: startsWith() and endsWith()
These work on whole names, not characters:
Path map = Path.of("/parks/alpine/lakes/blue.map");
map.startsWith("/parks"); // true
map.startsWith("/par"); // false: "par" isn't a complete name
map.endsWith("blue.map"); // true
map.endsWith("e.map"); // false
Compare map.toString().startsWith("/par"), which is true because String methods compare characters.
The real path: toRealPath()
toRealPath() asks the file system for the true location. It's the one method here that checks the disk:
- it makes a relative path absolute, like
toAbsolutePath(); - it removes redundant
.and.., likenormalize(); - it follows symbolic links to their targets, unless you pass
LinkOption.NOFOLLOW_LINKS; - it throws
IOException, typicallyNoSuchFileException, if the path doesn't exist.
// favourite is a symbolic link to alpine/lakes
Path.of("favourite/blue.map").toRealPath(); // /…/alpine/lakes/blue.map
Path.of(".").toRealPath(); // the current working directory
Files.createSymbolicLink(link, target) creates a link. Files.isSymbolicLink(path) tests for one.
Creating directories
public static Path createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException
public static Path createDirectories(Path dir, FileAttribute<?>... attrs) throws IOException
createDirectory | createDirectories | |
|---|---|---|
| Parent missing | NoSuchFileException | creates all missing parents |
| Directory already exists | FileAlreadyExistsException | does nothing, no error |
java.io.File equivalent | mkdir() | mkdirs() |
createDirectories is handy for making sure a directory exists. The optional FileAttribute values, such as POSIX permissions, are applied to the new directories.
Path method summary
| Description | Method |
|---|---|
| Whole path as text | String toString() |
| One name / number of names | Path getName(int) / int getNameCount() |
| Range of names | Path subpath(int begin, int end) |
| Last name / parent / root | getFileName() / getParent() / getRoot() |
| Join | resolve(Path), resolve(String), resolveSibling(...) |
| Steps from this path to another | relativize(Path) |
Remove redundant . and .. | normalize() |
| Absolute version | toAbsolutePath() |
| Real location on disk (needs the file) | toRealPath(LinkOption...) |
| Name-based prefix/suffix test | startsWith(...), endsWith(...) |
What's current
- Java 22 added
resolve(Path first, Path... more)andresolve(String first, String... more), for examplebase.resolve("a", "b", "c"). It doesn't compile with--release 21, so on the Java 21 examresolvetakes exactly one argument. Path.of(Java 11) is preferred overPaths.get.- The
Pathmethods themselves haven't changed since Java 7, so older study material still applies.
Exam traps from this article
A complete example
A national-park map service manipulates paths. The program shows immutability, names and subpath with every edge case, parent walks for absolute, relative and symbol-containing paths, resolve, relativize and normalize, and whole-name startsWith/endsWith. Then, in a temporary folder, it creates directories both ways, follows a real symbolic link with toRealPath(), and inspects a link whose target is missing.
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Stream;
public class Solution {
static void parents(Path path) {
StringBuilder sb = new StringBuilder();
for (Path p = path.getParent(); p != null; p = p.getParent()) sb.append(" -> ").append(p);
System.out.println(" " + path + ": fileName=" + path.getFileName() + ", root=" + path.getRoot()
+ ", parents" + (sb.length() == 0 ? ": none" : sb));
}
static void tryIt(String label, Runnable r) {
try {
r.run();
} catch (RuntimeException e) {
System.out.println(" " + label + " -> " + e.getClass().getSimpleName());
}
}
public static void main(String[] args) throws IOException {
System.out.println("== 1. Paths are immutable");
Path trail = Path.of("trails");
trail.resolve("north"); // result thrown away
System.out.println(" after ignoring resolve(): " + trail);
trail = trail.resolve("north"); // keep the new object
System.out.println(" after assigning it: " + trail);
System.out.println("\n== 2. Names, counts and subpath (the root is never a name)");
Path map = Path.of("/parks/alpine/lakes/blue.map");
for (int i = 0; i < map.getNameCount(); i++) System.out.println(" getName(" + i + "): " + map.getName(i));
System.out.println(" subpath(0, 2): " + map.subpath(0, 2) + ", subpath(1, 4): " + map.subpath(1, 4)
+ ", isAbsolute: " + map.subpath(0, 2).isAbsolute());
System.out.println(" Path.of(\"/\").getNameCount(): " + Path.of("/").getNameCount());
tryIt("Path.of(\"/\").getName(0)", () -> Path.of("/").getName(0));
tryIt("subpath(0, 5)", () -> map.subpath(0, 5));
tryIt("subpath(2, 2)", () -> map.subpath(2, 2));
System.out.println("\n== 3. getFileName, getRoot and getParent");
parents(Path.of("camp"));
parents(Path.of("/parks/alpine/hut.txt"));
parents(Path.of("./alpine/../hut.txt")); // symbols are just names here
System.out.println("\n== 4. resolve: think concatenation");
Path base = Path.of("/parks/../alpine");
System.out.println(" " + base + " resolve(\"lakes\"): " + base.resolve("lakes"));
System.out.println(" " + base + " resolve(\"/maps/x\"): " + base.resolve("/maps/x") + " (absolute argument wins)");
System.out.println(" lakes/blue.map resolveSibling(\"red.map\"): " + Path.of("lakes/blue.map").resolveSibling("red.map"));
System.out.println("\n== 5. relativize: how do I get from here to there?");
Path a = Path.of("camp.txt"), b = Path.of("alpine/lakes/blue.map");
System.out.println(" camp.txt -> alpine/lakes/blue.map: " + a.relativize(b));
System.out.println(" alpine/lakes/blue.map -> camp.txt: " + b.relativize(a));
Path from = Path.of("/parks/alpine"), to = Path.of("/parks/coast/bay/dock.txt");
System.out.println(" /parks/alpine -> /parks/coast/bay/dock.txt: " + from.relativize(to));
System.out.println(" resolve(relativize) gets back: " + from.resolve(from.relativize(to)).normalize());
tryIt("absolute.relativize(relative)", () -> from.relativize(Path.of("dock.txt")));
System.out.println("\n== 6. normalize: remove redundant . and ..");
for (String s : List.of("./alpine/../hut.txt", "/parks/../alpine/lakes", "../../camp.txt", "lakes/./blue/../red.map"))
System.out.println(" " + s + " -> " + Path.of(s).normalize());
Path x = Path.of("/parks/../camp.txt"), y = Path.of("/camp.txt");
System.out.println(" equals: " + x.equals(y) + ", after normalize: " + x.normalize().equals(y.normalize()));
System.out.println("\n== 7. startsWith / endsWith compare whole names, not characters");
System.out.println(" startsWith(\"/parks\"): " + map.startsWith("/parks") + ", startsWith(\"/par\"): " + map.startsWith("/par")
+ ", endsWith(\"blue.map\"): " + map.endsWith("blue.map") + ", endsWith(\"e.map\"): " + map.endsWith("e.map"));
System.out.println("\n== 8. Creating directories, toRealPath and symbolic links");
Path tmp = Files.createTempDirectory("parks").toRealPath(); // real path: no symlinks left in it
try {
try {
Files.createDirectory(tmp.resolve("alpine/lakes"));
} catch (NoSuchFileException e) {
System.out.println(" createDirectory with a missing parent -> NoSuchFileException");
}
Path lakes = Files.createDirectories(tmp.resolve("alpine/lakes"));
Files.createDirectories(lakes); // already there: no error
System.out.println(" createDirectories twice: fine, isDirectory=" + Files.isDirectory(lakes));
Files.writeString(lakes.resolve("blue.map"), "depth 40m");
Path shortcut = Files.createSymbolicLink(tmp.resolve("favourite"), lakes);
Path viaLink = shortcut.resolve("blue.map");
System.out.println(" via link: " + tmp.relativize(viaLink) + " -> toRealPath(): " + tmp.relativize(viaLink.toRealPath()));
System.out.println(" toRealPath(NOFOLLOW_LINKS) keeps the link: "
+ tmp.relativize(viaLink.toRealPath(LinkOption.NOFOLLOW_LINKS)));
Path messy = tmp.resolve("alpine/./lakes/../lakes/blue.map");
System.out.println(" toRealPath() also normalizes: " + tmp.relativize(messy.toRealPath()));
try {
tmp.resolve("alpine/missing.map").toRealPath();
} catch (NoSuchFileException e) {
System.out.println(" toRealPath() on a missing file -> NoSuchFileException (normalize() would not care)");
}
Path dangling = Files.createSymbolicLink(tmp.resolve("old-map"), tmp.resolve("gone.map"));
System.out.println(" link to a missing target: exists()=" + Files.exists(dangling)
+ ", exists(NOFOLLOW_LINKS)=" + Files.exists(dangling, LinkOption.NOFOLLOW_LINKS)
+ ", isSymbolicLink()=" + Files.isSymbolicLink(dangling));
} finally {
try (Stream<Path> all = Files.walk(tmp)) { // walk doesn't follow links
for (Path p : all.sorted(Comparator.reverseOrder()).toList()) Files.delete(p);
}
}
System.out.println(" temporary directory removed: " + Files.notExists(tmp));
}
}
Output:
== 1. Paths are immutable
after ignoring resolve(): trails
after assigning it: trails/north
== 2. Names, counts and subpath (the root is never a name)
getName(0): parks
getName(1): alpine
getName(2): lakes
getName(3): blue.map
subpath(0, 2): parks/alpine, subpath(1, 4): alpine/lakes/blue.map, isAbsolute: false
Path.of("/").getNameCount(): 0
Path.of("/").getName(0) -> IllegalArgumentException
subpath(0, 5) -> IllegalArgumentException
subpath(2, 2) -> IllegalArgumentException
== 3. getFileName, getRoot and getParent
camp: fileName=camp, root=null, parents: none
/parks/alpine/hut.txt: fileName=hut.txt, root=/, parents -> /parks/alpine -> /parks -> /
./alpine/../hut.txt: fileName=hut.txt, root=null, parents -> ./alpine/.. -> ./alpine -> .
== 4. resolve: think concatenation
/parks/../alpine resolve("lakes"): /parks/../alpine/lakes
/parks/../alpine resolve("/maps/x"): /maps/x (absolute argument wins)
lakes/blue.map resolveSibling("red.map"): lakes/red.map
== 5. relativize: how do I get from here to there?
camp.txt -> alpine/lakes/blue.map: ../alpine/lakes/blue.map
alpine/lakes/blue.map -> camp.txt: ../../../camp.txt
/parks/alpine -> /parks/coast/bay/dock.txt: ../coast/bay/dock.txt
resolve(relativize) gets back: /parks/coast/bay/dock.txt
absolute.relativize(relative) -> IllegalArgumentException
== 6. normalize: remove redundant . and ..
./alpine/../hut.txt -> hut.txt
/parks/../alpine/lakes -> /alpine/lakes
../../camp.txt -> ../../camp.txt
lakes/./blue/../red.map -> lakes/red.map
equals: false, after normalize: true
== 7. startsWith / endsWith compare whole names, not characters
startsWith("/parks"): true, startsWith("/par"): false, endsWith("blue.map"): true, endsWith("e.map"): false
== 8. Creating directories, toRealPath and symbolic links
createDirectory with a missing parent -> NoSuchFileException
createDirectories twice: fine, isDirectory=true
via link: favourite/blue.map -> toRealPath(): alpine/lakes/blue.map
toRealPath(NOFOLLOW_LINKS) keeps the link: favourite/blue.map
toRealPath() also normalizes: alpine/lakes/blue.map
toRealPath() on a missing file -> NoSuchFileException (normalize() would not care)
link to a missing target: exists()=false, exists(NOFOLLOW_LINKS)=true, isSymbolicLink()=true
temporary directory removed: true
Points to notice:
subpath(0, 2)of an absolute path was relative, andPath.of("/")had no names at all.- In the parent walk for
./alpine/../hut.txt,..and.were treated as ordinary names. resolve("/maps/x")ignored the base path completely.resolve(relativize(...))led back to the original target once normalized.toRealPath()turnedfavourite/blue.mapinto the realalpine/lakes/blue.map, and it also cleaned up a messy path, but it failed for a missing file.Files.exists()followed the dangling link and saidfalse. WithNOFOLLOW_LINKS, it found the link itself.
Common questions
What's the difference between normalize() and toRealPath()?
normalize() is pure text processing, and it works on paths that don't exist. toRealPath() asks the file system, so it makes the path absolute, follows links, and fails if the path is missing.
Why did relativize count three .. from alpine/lakes/blue.map?
The starting path is treated as a location in the tree, so its last name (blue.map) counts as one level to climb out of, then lakes, then alpine.
Does resolve add a separator if the base ends with one?
Path objects never keep a trailing separator. Path.of("/parks/") is just /parks, so resolve always produces a clean single separator.
Summary
Pathis immutable, and most of its methods only manipulate text.getNameCount,getNameandsubpathindex names from 0 and never include the root.getFileName,getParentandgetRootreturn parts of the path ornull.resolveappends, unless the argument is absolute.relativizegives directions between two paths of the same kind.normalizeremoves redundant.and...toRealPath()checks the disk and follows links.createDirectorymakes one directory, andcreateDirectoriesmakes the whole chain.
Practice quiz
Test yourself with the Path methods quiz: 10 exam-style questions with explanations.
Previous: Java File and Path: Creating Paths and Converting Between Them (OCP 21)
Next: Java Files: Copying, Moving, Deleting and Comparing Files (OCP 21)
Related reading
- Java File and Path: Creating Paths and Converting Between Them (OCP 21)
- Java Parallel Streams: Parallel Decomposition, Reductions and Ordering (OCP 21)
- Java Concurrent Collections and Threading Problems: Deadlock, Starvation and Livelock (OCP 21)
- Java Locks: ReentrantLock, tryLock, ReadWriteLock and CyclicBarrier (OCP 21)
- Java Thread Safety: Race Conditions, volatile, Atomic Classes and synchronized (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.