Sub topic 1
Representing locations with Path
Prerequisites
This chapter assumes you can write and run a small Java program with a main method. It also assumes you know what a String is, what a checked exception is, and that you have Java 11 or later installed. Examples use Linux or macOS paths. Where Windows behaves differently, the text says so.
What a Path is
A java.nio.file.Path is an object that represents a location in a file system. It is a structured value made of a root (optional) and a sequence of name elements, such as home, ana, docs and a.txt.
A Path is only a name. Creating one does not open a file, check that it exists, or touch the disk. You can build a Path to a file that does not exist yet, which is what you need before you create it.
A Path is also immutable. Every method that seems to change a path returns a new Path and leaves the original alone. This is the same design as String.
Path is an interface. The concrete class depends on the platform, so you never write new Path(...). You ask for one through a factory method.
Creating paths
Since Java 11, the standard factory is Path.of:
import java.nio.file.Path;
public class CreatePaths {
public static void main(String[] args) {
Path one = Path.of("data/notes.txt");
Path two = Path.of("data", "notes.txt");
Path three = Path.of("/home/ana/docs/a.txt");
System.out.println(one);
System.out.println(two);
System.out.println(one.equals(two));
System.out.println(three);
}
}On Linux or macOS this prints:
data/notes.txt
data/notes.txt
true
/home/ana/docs/a.txtThe second form passes the path in pieces: Path.of(String first, String... more). Java joins the pieces with the platform's separator, which is / on Linux and macOS and \ on Windows. Building paths from pieces keeps your code portable, because you never type a separator yourself. Empty pieces are ignored.
You can also build a path from a java.net.URI with Path.of(URI). The URI must be absolute and use a scheme such as file:. This is less common, and you will mostly start from strings.
Invalid paths
Path.of throws InvalidPathException when the string cannot be a path on the current system. This is an unchecked exception, so the compiler does not force you to catch it. A common cause is a user-supplied string containing a character the file system rejects, such as the NUL character on Linux, or ? and * on Windows.
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
public class BadPath {
public static void main(String[] args) {
try {
Path p = Path.of("bad\0name");
System.out.println(p);
} catch (InvalidPathException e) {
System.out.println("Rejected: " + e.getReason());
}
}
}Catch InvalidPathException at the place where you accept outside input, such as command-line arguments, a configuration file or a web form.
Absolute and relative paths
An absolute path is complete by itself. It starts at a root: / on Linux and macOS, or a drive such as C:\ on Windows. A relative path has no root. It is interpreted against some starting directory.
For a relative path, the starting directory is the process's current working directory. Java reads it from the user.dir system property when the program starts. If you launch your program from /home/ana/project, then Path.of("data/notes.txt") refers to /home/ana/project/data/notes.txt. If you launch the same program from another directory, the same relative path points somewhere else.
toAbsolutePath() makes this explicit. It returns a new path with the working directory placed in front of a relative path. It does nothing to a path that is already absolute.
import java.nio.file.Path;
public class AbsoluteDemo {
public static void main(String[] args) {
Path relative = Path.of("data", "notes.txt");
System.out.println(relative.isAbsolute());
System.out.println(relative.toAbsolutePath());
System.out.println(System.getProperty("user.dir"));
}
}The second and third lines show the same directory at the start. Printing toAbsolutePath() is a quick way to debug a "file not found" error, because it shows where Java is really looking.
Taking a path apart
A Path has accessor methods for each part. The table uses the Linux path /home/ana/docs/a.txt.
| Method | Result | Meaning |
|---|---|---|
| `getRoot()` | `/` | The root, or `null` for a relative path |
| `getParent()` | `/home/ana/docs` | Everything except the last element, or `null` if there is none |
| `getFileName()` | `a.txt` | The last name element, as a `Path` |
| `getNameCount()` | `4` | Number of name elements, not counting the root |
| `getName(0)` | `home` | The name element at a zero-based index |
| `subpath(1, 3)` | `ana/docs` | A relative path from index 1 up to, but not including, index 3 |
| `isAbsolute()` | `true` | Whether the path has a root |
The next program prints all of these values:
import java.nio.file.Path;
public class Anatomy {
public static void main(String[] args) {
Path p = Path.of("/home/ana/docs/a.txt");
System.out.println("root = " + p.getRoot());
System.out.println("parent = " + p.getParent());
System.out.println("fileName = " + p.getFileName());
System.out.println("nameCount = " + p.getNameCount());
System.out.println("name(0) = " + p.getName(0));
System.out.println("subpath = " + p.subpath(1, 3));
for (Path part : p) {
System.out.println("element: " + part);
}
}
}Path implements Iterable<Path>, so the enhanced for loop visits each name element in order. The loop does not include the root.
Null results
Several of these methods return null. getRoot() returns null for a relative path. getParent() returns null for a path with a single element, such as Path.of("notes.txt"), and for a bare root. getFileName() returns null for a bare root such as /.
This matters when you chain calls. The expression Path.of("notes.txt").getParent().resolve("x") throws NullPointerException, because the parent of a one-element relative path is null. Check for null, or call toAbsolutePath() first, when the input is not under your control.
Comparing paths
Path overrides equals, hashCode and compareTo, so you can use paths as map keys and sort them. Equality compares the path elements, not the files they point to. On Windows the comparison ignores case, and on Linux it is case-sensitive.
import java.nio.file.Path;
public class Compare {
public static void main(String[] args) {
Path a = Path.of("/home/ana");
Path b = Path.of("/home/ana/");
Path c = Path.of("/home/ana/../ana");
System.out.println(a.equals(b));
System.out.println(a.equals(c));
System.out.println(a.startsWith("/home"));
System.out.println(a.startsWith("/ho"));
System.out.println(Path.of("a/b/c.txt").endsWith("c.txt"));
}
}The output is true, false, true, false, true. A trailing slash is dropped when the path is created, so a and b are equal. Path c has different elements, so it is not equal to a, even though both name the same directory. Cleaning up .. elements is covered in the next chapter.
startsWith and endsWith compare whole name elements, not characters. That is why /home/ana does not start with /ho. Comparing toString() results with String.startsWith would give the wrong answer here.
Common mistakes
- Assuming the file exists.
Path.of("missing.txt")succeeds. The error appears later, when you try to read the file. - Joining with string concatenation.
"data" + "/" + namefails on Windows and produces odd results whennamealready starts with a separator. UsePath.of("data", name). - Depending on the working directory. A relative path behaves differently when the program is started from an IDE, a script or a scheduler. Print
toAbsolutePath()while debugging. - Dereferencing
null. Check the results ofgetParent()andgetRoot(). - Comparing paths as strings. Compare
Pathobjects, or usestartsWithon aPath.
Exercise
Given Path p = Path.of("reports", "2026", "summary.txt"); on Linux, what do p.getNameCount(), p.getParent() and p.getRoot() return?
Show answer
getNameCount() returns 3, because the path has three name elements. getParent() returns the relative path reports/2026. getRoot() returns null, because the path is relative and has no root.
Exercise
A program calls Path.of("config.properties").getParent().resolve("backup") and crashes with a NullPointerException. Why does it crash, and how can you fix it?
Show answer
A relative path with a single name element has no parent, so getParent() returns null, and calling resolve on null throws the exception. Fix it by calling toAbsolutePath() first, as in Path.of("config.properties").toAbsolutePath().getParent(), or by checking the result of getParent() for null before using it.