Java File Paths
What a Path Is
A path identifies the location of a file or folder in a file system. It is a sequence of names separated by a separator character, optionally starting from a root:
/home/asha/app/reports/2026/sales.csv
│ └──┬─┘ └┬┘ └──┬──┘ └┬─┘ └───┬───┘
root name name name name file name
In Java, a path is represented by the interface java.nio.file.Path. A Path object is just a structured description of a location — creating or manipulating one never touches the disk. The file it describes may or may not exist. Operations that need the actual file (reading, checking existence, resolving links) are done through Files or a few specific Path methods such as toRealPath.
This separation is useful: you can build, combine and validate paths freely, and only when you perform an I/O operation does the file system get involved.
Creating Path Objects
Path a = Path.of("/home/asha/app/config.yaml"); // one string
Path b = Path.of("reports", "2026", "sales.csv"); // several parts joined with the separator
Path c = Paths.get("reports", "2026", "sales.csv"); // older equivalent (Java 7)
Path d = new java.io.File("notes.txt").toPath(); // from a java.io.File
Path.of(Java 11+) is the standard way. Passing parts separately lets Java insert the right separator for the operating system, soPath.of("reports", "2026", "sales.csv")becomesreports/2026/sales.csvon Linux andreports\2026\sales.csvon Windows.Paths.getdoes exactly the same thing and is still common in code written for Java 7–10.Path.of(...).equals(Paths.get(...))istrue.- An invalid path string — for example one containing a character the operating system forbids, such as
:in a Windows file name or a NUL character — throwsInvalidPathException(unchecked) immediately.
Inspecting the Parts of a Path
import java.nio.file.*;
public class P1 {
public static void main(String[] args) {
Path p = Path.of("/home/asha/app/reports/2026/sales.csv");
System.out.println("toString: " + p);
System.out.println("getFileName: " + p.getFileName());
System.out.println("getParent: " + p.getParent());
System.out.println("getRoot: " + p.getRoot());
System.out.println("isAbsolute: " + p.isAbsolute());
System.out.println("getNameCount: " + p.getNameCount());
System.out.println("getName(0): " + p.getName(0));
System.out.println("subpath(3,5): " + p.subpath(3, 5));
Path rel = Path.of("reports", "2026", "sales.csv");
System.out.println("relative: " + rel + ", root=" + rel.getRoot() + ", absolute=" + rel.isAbsolute());
System.out.println("single name parent: " + Path.of("sales.csv").getParent());
for (Path part : rel) System.out.print("[" + part + "] ");
System.out.println();
}
}
Output (on Linux or macOS):
toString: /home/asha/app/reports/2026/sales.csv
getFileName: sales.csv
getParent: /home/asha/app/reports/2026
getRoot: /
isAbsolute: true
getNameCount: 6
getName(0): home
subpath(3,5): reports/2026
relative: reports/2026/sales.csv, root=null, absolute=false
single name parent: null
[reports] [2026] [sales.csv]
| Method | Returns |
|---|---|
getFileName() | The last name — the file or folder name itself |
getParent() | Everything except the last name, or null if there's no parent |
getRoot() | The root (/ on Unix, C: 0 on Windows), or null` for a relative path |
isAbsolute() | Whether the path starts from a root |
getNameCount() | How many names there are, not counting the root (6 here) |
getName(i) | The name at index i, where index 0 is closest to the root |
subpath(begin, end) | The names from begin (inclusive) to end (exclusive), as a relative path |
Every return value is itself a Path (except isAbsolute and getNameCount), so you can call more methods on it. A Path is also Iterable<Path>, so the for loop visits each name in order.
Watch for null: Path.of("sales.csv").getParent() returns null because a single relative name has no parent in the path, even though the file is obviously in some folder on disk. Code such as Files.createDirectories(path.getParent()) throws NullPointerException for such paths; calling toAbsolutePath() first guarantees a parent exists.
Absolute and Relative Paths
| Absolute path | Relative path | |
|---|---|---|
| Starts with | A root (/, `C:`) | A name |
| Example | /srv/shop/uploads/logo.png | uploads/logo.png |
| Resolved against | Nothing — it's complete | The current working directory (user.dir) |
| Same meaning on every run? | Yes | Only if the program is started from the same folder |
toAbsolutePath() turns a relative path into an absolute one by prepending the working directory. It doesn't check that the file exists and doesn't remove .. or . segments — it's purely textual.
Path.of(""), the empty path, refers to the working directory itself; Path.of("").toAbsolutePath() is a convenient way to get it as a Path.
Combining Paths: resolve, resolveSibling and relativize
import java.nio.file.*;
public class P2 {
public static void main(String[] args) {
Path base = Path.of("/srv/shop");
System.out.println("resolve: " + base.resolve("uploads/logo.png"));
System.out.println("resolve absolute: " + base.resolve("/etc/passwd"));
Path file = base.resolve("config/app.yaml");
System.out.println("resolveSibling: " + file.resolveSibling("app.yaml.bak"));
System.out.println("relativize: " + base.relativize(Path.of("/srv/shop/uploads/2026/a.png")));
System.out.println("relativize up: " + Path.of("/srv/shop/uploads").relativize(Path.of("/srv/shop/config/app.yaml")));
Path messy = Path.of("/srv/shop/uploads/../config/./app.yaml");
System.out.println("normalize: " + messy.normalize());
System.out.println("relative normalize: " + Path.of("../../data/./x.csv").normalize());
System.out.println("startsWith path: " + Path.of("/srv/shop-backup/x").startsWith(base));
System.out.println("startsWith string:" + Path.of("/srv/shop-backup/x").toString().startsWith(base.toString()));
System.out.println("equals: " + Path.of("/srv/shop/./a").equals(Path.of("/srv/shop/a")));
System.out.println("equals normalized:" + Path.of("/srv/shop/./a").normalize().equals(Path.of("/srv/shop/a")));
}
}
Output (on Linux or macOS):
resolve: /srv/shop/uploads/logo.png
resolve absolute: /etc/passwd
resolveSibling: /srv/shop/config/app.yaml.bak
relativize: uploads/2026/a.png
relativize up: ../config/app.yaml
normalize: /srv/shop/config/app.yaml
relative normalize: ../../data/x.csv
startsWith path: false
startsWith string:true
equals: false
equals normalized:true
resolve
base.resolve(other) appends other to base — the safe, portable way to build a path inside a folder, instead of string concatenation with "/". One rule surprises many developers: if other is absolute, resolve returns other unchanged. base.resolve("/etc/passwd") is simply /etc/passwd. This matters a great deal when other comes from user input (see the practical example below).
resolveSibling
resolveSibling(name) replaces the last name, producing a path in the same folder — ideal for backup copies (app.yaml.bak), temporary files next to the target, or changing an extension.
relativize
a.relativize(b) answers "how do I get from a to b?". From /srv/shop to /srv/shop/uploads/2026/a.png is uploads/2026/a.png; from /srv/shop/uploads to /srv/shop/config/app.yaml requires going up one level first, ../config/app.yaml. It's used to display paths relative to a project folder, or to recreate a folder structure elsewhere: target.resolve(source.relativize(file)). Both paths must be of the same type (both absolute or both relative), otherwise it throws IllegalArgumentException.
normalize
normalize() removes redundant segments: . (the current folder) is dropped, and name/.. pairs cancel out. It's purely textual and doesn't consult the file system, which has two consequences:
- Leading
..segments in a relative path can't be removed, because there's nothing before them to cancel (../../data/x.csvstays as it is apart from the.). - If a folder in the path is a symbolic link,
link/..on disk goes to the link target's parent, not to the folder that contains the link, so the normalized path can differ from where the file system would really go.toRealPath()(below) is the reliable alternative when links may be involved.
startsWith and equals compare names, not text
Path.startsWith(Path)compares whole names./srv/shop-backup/xdoes not start with/srv/shop, becauseshop-backupandshopare different names. The string comparison saystrue, which is the classic bug in hand-written path checks.Path.equalscompares the path as written (case-sensitively on Linux, case-insensitively on Windows)./srv/shop/./aand/srv/shop/adescribe the same location but aren't equal until normalized. Neither method follows links or checks the disk.
Real Paths and Symbolic Links
toRealPath() asks the file system for the canonical location: it makes the path absolute, resolves . and .., and follows symbolic links. Unlike the other methods, it requires the file to exist.
import java.io.IOException;
import java.nio.file.*;
public class P3 {
public static void main(String[] args) throws IOException {
Path release = Files.createDirectories(Path.of("releases", "v2.4.1"));
Files.writeString(release.resolve("app.jar"), "jar");
Path current = Path.of("current");
Files.deleteIfExists(current);
Files.createSymbolicLink(current, release);
Path viaLink = Path.of("current/app.jar");
System.out.println("toAbsolutePath: " + viaLink.toAbsolutePath());
System.out.println("toRealPath: " + viaLink.toRealPath());
System.out.println("equals: " + viaLink.equals(Path.of("releases/v2.4.1/app.jar")));
System.out.println("isSameFile: " + Files.isSameFile(viaLink, Path.of("releases/v2.4.1/app.jar")));
try {
Path.of("missing/file.txt").toRealPath();
} catch (NoSuchFileException e) {
System.out.println("toRealPath on a missing path: NoSuchFileException");
}
}
}
Output (run in /home/asha/demo on Linux; creating symbolic links on Windows requires Developer Mode or administrator rights):
toAbsolutePath: /home/asha/demo/current/app.jar
toRealPath: /home/asha/demo/releases/v2.4.1/app.jar
equals: false
isSameFile: true
toRealPath on a missing path: NoSuchFileException
currentis a symbolic link toreleases/v2.4.1— a common deployment layout, where switching versions means repointing one link.toAbsolutePath()only prepends the working directory; the link is still in the path.toRealPath()follows the link and shows where the file physically is. PassLinkOption.NOFOLLOW_LINKSto resolve the path without following links.equalscompares text, so the two paths aren't equal.Files.isSameFile(a, b)asks the file system whether both paths lead to the same file, which is the correct way to check this.
Separators and Operating System Differences
| Linux / macOS | Windows | |
|---|---|---|
| Name separator | / | |