Course contentsShow
← Java
Lesson 2033 of 2,87041. NIO.2 and the Path APIFree lesson

Path Comparison and Iteration

Compare paths with equals(), startsWith(), endsWith(), and iterate over path components using the Iterable interface.

Path Comparison and Iteration

What you'll learn: How to compare Path objects for equality and containment, and how to iterate through individual path components.

Comparing Paths

Not all paths that point to the same file are equal as objects. The equals() method compares paths lexically (by their string representation), not by what they reference on disk. Two paths like "/home/user/file.txt" and "/home/user/../user/file.txt" might point to the same file but won't be equal until normalized.

The startsWith() and endsWith() methods check if a path begins or ends with another path component-wise, not as simple string prefixes. For example, "/home/user/docs" starts with "/home/user" but not with "/home/use" (partial component names don't count).

Path p1 = Paths.get("/home/user/docs/file.txt");
Path p2 = Paths.get("/home/user/docs/file.txt");
Path p3 = Paths.get("/home/user");

System.out.println(p1.equals(p2));        // true (identical strings)
System.out.println(p1.startsWith(p3));    // true (component match)
System.out.println(p1.endsWith("file.txt")); // true

Iterating Over Path Components

Path implements Iterable<Path>, allowing you to loop through each component (directory or file name) separately. Think of it like breaking a file path into breadcrumbs:

Path path = Paths.get("/home/user/docs/file.txt");

for (Path component : path) {
    System.out.println(component);
}
// Outputs: home, user, docs, file.txt

Notice the root (/) is not included in iteration—use getRoot() separately if needed.

Key Takeaway:
Use equals(), startsWith(), and endsWith() for lexical path comparison (component-aware, not string prefixes), and leverage Path's Iterable interface to process individual path segments in a loop.