When working with files and directories, we usually need to represent locations in the file system. Object of the type Path represents a path to a file or directory. It does not necessarily mean that the file or the directory actually exist. It simply represents a location in a file system.
The Path API also provides us with convenient operations for combining paths, extracting parts of a path, normalizing paths, converting between relative and absolute paths, and working with the Files class.
The Path Interface
Path is part of the java.nio.file package. Despite often being referred to informally as the “Path class,” Path is actually an interface. We can easily create a simple Path object by calling the Path.of() method.
public class PathDemo {
public static void main(String[] args) {
Path path = Path.of("data", "books.txt");
System.out.println(path);
}
}
The output when running this code sample will be the following:
data/books.txt
Creating Paths with Path.of()
Modern Java code can create a Path using the static Path.of() factory method.
Path path = Path.of("finance", "reports","2026", "annual-report.pdf");
System.out.println(path);
The output when running this code will be:
finance/reports/2026/annual-report.pdf
The Paths Class
Java also provides the java.nio.file.Paths class. Paths is a utility class whose main purpose is creating Path objects.
Path path = Paths.get("finance", "reports","2026", "annual-report.pdf");
System.out.println(path);
The output when running this code will be:
finance/reports/2026/annual-report.pdf
The relativize() Method
The relativize() method calculates the path needed to move from one path to another.
Path source = Path.of(
"/projects/ngager"
);
Path target = Path.of(
"/projects/prompo/app.json"
);
Path relative =
source.relativize(target);
System.out.println(relative);
The output will be:
../prompo/app.json
The Path API is much more than a replacement for storing file names as strings. It gives Java a structured abstraction for representing locations in a file system and provides operations for composing, inspecting, comparing, normalizing, and transforming paths.







