Java NIO Path: Creating, Resolving, Relativizing and Normalizing Paths
Work with file system paths using java.nio.file.Path: Path.of, absolute and relative paths, resolve and Java 22's multi-argument resolve, resolveSibling, relativize, normalize, toAbsolutePath, taking paths apart, startsWith, URIs and the legacy File class.
kvi5hnuCode Sprout team member8 min readOn this page
So far this part has been about the contents of files: reading and writing bytes and characters. Programs also need to manage files themselves: build file names, create directories, copy, move and delete files, list directory contents and query sizes and timestamps. Since Java 7, the Path interface and the Files class in java.nio.file do that job. They replace the java.io.File class from Java 1.0, which had confusing error handling (many methods just returned false) and limited features. Use File only to talk to legacy APIs.
This article covers Path, the representation of a location. The next three cover Files, which does the actual work.
Creating paths
A Path is a sequence of names: directory names, optionally followed by a file name. The first component may be a root such as / on Unix or C:\ on Windows. A path that starts with a root is absolute, and one without is relative:
Path absolute = Path.of("/home", "maya"); // Unix-style example
Path relative = Path.of("appconf", "conf", "user.properties");
Path.of (Java 11, previously Paths.get) joins its arguments with the file system's separator, / on Unix and \ on Windows, and parses the result. If the string isn't a valid path in the file system, it throws an InvalidPathException. A single string with separators in it works fine, so you can take a path straight from a configuration file:
Path basePath = Path.of(props.getProperty("base.dir")); // "/opt/appconf" or "C:\Program Files\appconf"
A Path is just a name. It doesn't have to exist. Creating a Path never touches the disk. You create a path first, then call a Files method to create, read or check the corresponding file.
Path objects are immutable, and every operation below returns a new path.
Combining paths: resolve
p.resolve(q) combines two paths:
- If
qis absolute, the result isq. - Otherwise, the result is
qappended top.
Path workPath = basePath.resolve("work"); // /opt/myapp/work
Path logPath = basePath.resolve("data", "2026", "log.txt"); // Java 22: several names at once
There's a String overload, so you rarely need to create a Path for the argument. resolveSibling resolves against the parent, giving a path next to the original: if workPath is /opt/myapp/work, then workPath.resolveSibling("temp") is /opt/myapp/temp.
resolve doesn't simplify anything: Path.of("/usr/bin").resolve("../local") is /usr/bin/../local.
Simplifying and comparing: normalize and relativize
normalize() removes redundant . and name/.. elements: /home/maya/../sam/./input.txt becomes /home/sam/input.txt. It works purely on the text. It doesn't check the disk, so with symbolic links the result can point somewhere else than the original. toRealPath() (next article) resolves links against the actual file system.
relativize is the opposite of resolve: p.relativize(r) yields the path q such that p.resolve(q) leads to r. Relativizing /home/sam/input.txt against /home/maya gives ../sam/input.txt. Both paths must be of the same kind, both absolute or both relative.
toAbsolutePath() turns a relative path into an absolute one by resolving it against the working directory (System.getProperty("user.dir")). An absolute path is returned unchanged.
Taking paths apart
Path p = Path.of("/home", "sam", "appconf.properties");
Path parent = p.getParent(); // /home/sam
Path file = p.getFileName(); // appconf.properties
Path root = p.getRoot(); // /
getParent()returnsnullfor a path with no parent, such asPath.of("file.txt")or/.getFileName()returns the last component, which may be a directory name.getRoot()returnsnullfor a relative path.getNameCount(),getName(i)andsubpath(from, to)access the components, not counting the root.- A
PathisIterable<Path>, sofor (Path part : p)visitshome,samandappconf.properties.
There's no built-in method for the file extension. Use the file name: name.substring(name.lastIndexOf('.') + 1) after checking that a dot exists.
Comparing paths
equals and compareTo compare paths textually. /home/sam/../sam/x doesn't equal /home/sam/x, though they name the same file. Normalize first, or use Files.isSameFile (next article), which asks the file system. Comparisons are case-sensitive on Unix and case-insensitive on Windows.
startsWith and endsWith compare whole name elements, not characters: /home/sam starts with /home but not with /home/fr. That's exactly what you want for checks like "is this file inside that directory?", the zip slip check from the previous article.
Paths, URIs and Files
path.toUri()gives afile:URI with special characters escaped, such asfile:///tmp/report%20final.pdf.Path.of(uri)goes back. URIs are how paths in other file systems, such as ZIP file systems, are named.path.toFile()andfile.toPath()convert betweenPathand the legacyjava.io.File.FileSystems.getDefault().getSeparator()returns the separator string. You rarely need it, becausePath.ofandresolvehandle separators for you.
Most java.io classes that take a File also have counterparts in Files that take a Path, such as Files.newInputStream, and Scanner has a Path constructor. PrintWriter is a notable exception (article 20).
A complete example
import java.io.File;
import java.net.URI;
import java.nio.file.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
// absolute and relative paths (Unix-style examples)
Path absolute = Path.of("/home", "maya");
Path relative = Path.of("appconf", "conf", "user.properties");
System.out.println(absolute + " absolute: " + absolute.isAbsolute());
System.out.println(relative + " absolute: " + relative.isAbsolute());
System.out.println("one string with separators: " + Path.of("/opt/appconf/lib"));
// resolve, resolveSibling
Path basePath = Path.of("/opt/myapp");
Path workPath = basePath.resolve("work");
System.out.println("resolve: " + workPath);
System.out.println("resolve an absolute path: " + basePath.resolve("/etc/hosts"));
System.out.println("resolve several (Java 22): " + basePath.resolve("data", "2026", "log.txt"));
System.out.println("resolveSibling: " + workPath.resolveSibling("temp"));
System.out.println("resolve doesn't simplify: " + Path.of("/usr/bin").resolve("../local"));
// normalize and relativize
System.out.println("normalize: " + Path.of("/home/maya/../sam/./input.txt").normalize());
Path maya = Path.of("/home/maya");
Path samInput = Path.of("/home/sam/input.txt");
Path rel = maya.relativize(samInput);
System.out.println("relativize: " + rel);
System.out.println("resolve it back: " + maya.resolve(rel).normalize());
// taking a path apart
Path p = Path.of("/home", "sam", "appconf.properties");
System.out.println("parent: " + p.getParent() + ", file name: " + p.getFileName() + ", root: " + p.getRoot());
System.out.println("name count: " + p.getNameCount() + ", name(1): " + p.getName(1) + ", subpath(0, 2): " + p.subpath(0, 2));
var names = new ArrayList<String>();
for (Path part : p) names.add(part.toString());
System.out.println("iterating: " + names);
System.out.println("relative path has no root: " + relative.getRoot());
// file name extension, the manual way
String fileName = p.getFileName().toString();
int dot = fileName.lastIndexOf('.');
System.out.println("extension: " + (dot > 0 ? fileName.substring(dot + 1) : ""));
// startsWith compares whole names, not characters
System.out.println("/home/sam startsWith /home/fr: " + Path.of("/home/sam").startsWith("/home/fr"));
System.out.println("/home/sam startsWith /home: " + Path.of("/home/sam").startsWith("/home"));
System.out.println("endsWith sam/appconf.properties: " + p.endsWith("sam/appconf.properties"));
// equality is textual
Path a = Path.of("/home/sam/../sam/x"), b = Path.of("/home/sam/x");
System.out.println("equal before normalize: " + a.equals(b) + ", after: " + a.normalize().equals(b));
// relative paths are resolved against the working directory
Path cwd = Path.of("").toAbsolutePath();
System.out.println("toAbsolutePath uses user.dir: " + cwd.toString().equals(System.getProperty("user.dir")));
System.out.println("data.txt -> " + Path.of("data.txt").toAbsolutePath().equals(cwd.resolve("data.txt")));
// URIs and legacy File objects
URI uri = Path.of("/tmp/report final.pdf").toUri();
System.out.println("URI: " + uri);
System.out.println("back from URI: " + Path.of(uri));
File legacy = p.toFile();
System.out.println("File: " + legacy + ", toPath equal: " + legacy.toPath().equals(p));
// invalid paths
try {
Path.of("bad\0name");
} catch (InvalidPathException e) {
System.out.println("InvalidPathException: " + e.getReason());
}
System.out.println("separator: " + FileSystems.getDefault().getSeparator());
}
}
/home/maya absolute: true
appconf/conf/user.properties absolute: false
one string with separators: /opt/appconf/lib
resolve: /opt/myapp/work
resolve an absolute path: /etc/hosts
resolve several (Java 22): /opt/myapp/data/2026/log.txt
resolveSibling: /opt/myapp/temp
resolve doesn't simplify: /usr/bin/../local
normalize: /home/sam/input.txt
relativize: ../sam/input.txt
resolve it back: /home/sam/input.txt
parent: /home/sam, file name: appconf.properties, root: /
name count: 3, name(1): sam, subpath(0, 2): home/sam
iterating: [home, sam, appconf.properties]
relative path has no root: null
extension: properties
/home/sam startsWith /home/fr: false
/home/sam startsWith /home: true
endsWith sam/appconf.properties: true
equal before normalize: false, after: true
toAbsolutePath uses user.dir: true
data.txt -> true
URI: file:///tmp/report%20final.pdf
back from URI: /tmp/report final.pdf
File: /home/sam/appconf.properties, toPath equal: true
InvalidPathException: Nul character not allowed
separator: /
Common questions
Should I replace File with Path everywhere?
In new code, yes: Path and Files have better error reporting, symbolic link support and many more operations. Existing code using File keeps working, and toPath() and toFile() make gradual migration easy.
Is Path.of different from Paths.get?
No. Paths.get was the Java 7 way, and Path.of (Java 11) is the same method on the interface itself. The documentation recommends Path.of, and Paths.get may be deprecated in the future.
How do I get a file name without its extension?
String name = path.getFileName().toString(); int dot = name.lastIndexOf('.'); String base = dot > 0 ? name.substring(0, dot) : name;. Testing dot > 0 keeps hidden files such as .bashrc intact.
Are paths compared case-insensitively on macOS?
No. Path.equals on macOS is case-sensitive, even though the default APFS file system is not, so /tmp/A and /tmp/a are unequal paths that may name the same file. Files.isSameFile asks the file system and gives the right answer.
How do I check that a user-supplied path stays inside a base directory?
Path resolved = base.resolve(userInput).normalize(); if (!resolved.startsWith(base.normalize())) throw .... If symbolic links are involved, compare toRealPath() results instead, because a link inside the directory can point outside it.
What does a relative path refer to in a web server or IDE?
The working directory, which is wherever the JVM was started: often the project directory in an IDE, but something else in a server or a service. Do not rely on it for files that belong to the application. Use configuration, user.home, or class path resources (article 18).
API reference
java.nio.file.Path
| Method | Description |
|---|---|
static Path of(String first, String... more) (Java 11), static Path of(URI uri) | makes a path by joining strings, or from a URI |
Path resolve(Path other), resolve(String other) | other if it's absolute, otherwise other appended to this path |
Path resolve(String first, String... more), resolve(Path first, Path... more) (Java 22) | resolves several names in turn |
Path resolveSibling(Path other), resolveSibling(String other) | resolves against this path's parent |
Path relativize(Path other) | the relative path that leads from this path to other |
Path normalize() | removes redundant . and .. elements |
Path toAbsolutePath() | resolves against the working directory if relative |
boolean isAbsolute() | whether the path has a root |
Path getParent(), getFileName(), getRoot() | parent, last element and root, or null |
int getNameCount(), Path getName(int index), Path subpath(int begin, int end) | access to the name elements |
boolean startsWith(String other), endsWith(String other) (and Path overloads) | compare whole name elements |
URI toUri(), File toFile() | convert to a URI or a legacy File |
java.io.File
| Method | Description |
|---|---|
Path toPath() (Java 7) | the Path for this file |
Summary
Pathrepresents a location in a file system. It's immutable, and creating one never touches the disk.Path.ofjoins components with the right separator. Paths with a root are absolute.resolveappends,resolveSiblingreplaces the last element, andrelativizecomputes the way from one path to another.normalizeremoves.and..textually, andtoAbsolutePathresolves against the working directory.getParent,getFileName,getRoot, name iteration andsubpathtake paths apart.startsWithandendsWithwork element by element.- Equality is textual. Use
toUri,toFileandFile.toPathto convert.
Practice Questions
What do Path.of("/a/b").resolve("c") and Path.of("/a/b").resolve("/c") return?
/a/b/c and /c. A relative argument is appended, but an absolute argument is returned as is.
What is Path.of("/data/in/report.csv").resolveSibling("report.bak")?
/data/in/report.bak. The argument replaces the last element, because it's resolved against the parent /data/in.
Compute the path from /var/www/site/css to /var/www/site/img/logo.png.
Path.of("/var/www/site/css").relativize(Path.of("/var/www/site/img/logo.png")) returns ../img/logo.png.
Is Path.of("/srv/app2/config").startsWith(Path.of("/srv/app")) true? Why does it matter?
No. startsWith compares whole name elements, and app2 isn't app. A string comparison would wrongly say yes, which is a classic bug in "is this file inside that directory?" security checks.
Why might Path.of("a/../b").equals(Path.of("b")) be false even though both name the same file?
equals compares the path text, and the two strings differ. Normalize both paths first, or use Files.isSameFile, which checks the actual file system and also handles symbolic links.
Previous: Java ZIP Archives: ZipInputStream, ZipOutputStream and ZIP File Systems
Next: Java Files: Reading, Writing and Creating Files and Directories
Related reading
- Java ZIP Archives: ZipInputStream, ZipOutputStream and ZIP File Systems
- Java RandomAccessFile: Seeking and Fixed-Size Records
- Java DataInput and DataOutput: Reading and Writing Binary Data
- Java Character Encodings: UTF-8, Charsets and the Default Encoding
- Java Text Input and Output: PrintWriter, BufferedReader and Saving Objects as Text

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.