Java Programming Tutorials

Java programming tutorials with many code examples!

Java find relative path

Java find relative path

In this tutorial we’re going to show how to find relative paths between directories using java.nio.file.Path from Java NIO.

Relative path between absolute paths

Finding relative path between two absolute paths works perfectly fine:

Path path1 = Paths.get("/user1/bin");
Path path2 = Paths.get("/user2/bin");

System.out.printf("Path from %s to %s: %s%n",
    path1, path2, path1.relativize(path2));

The code produces a nice path:

Path from /user1/bin to /user2/bin: ../user2/bin

Relative path between relative paths

Path path1 = Paths.get("bin");
Path path2 = Paths.get("doc");
System.out.printf("Path from %s to %s: %s%n",
    path1, path2, path1.relativize(path2));

Calculated path is:

Path from bin to doc: ../doc

Relative path between absolute and relative paths

try {
    Path path1 = Paths.get("/user1/bin");
    Path path2 = Paths.get("doc");
    path1.relativize(path2);
} catch (IllegalArgumentException e) {
    System.out.printf("Path from %s to %s:%n%s",
        path1, path2, e);
}

Unfortunately the result is IllegalArgumentException:

Path from /user1/bin to doc:
java.lang.IllegalArgumentException: 'other' is different type of Path

When one of the paths is relative and the other one is absolute Path.relativize() will throw the exception with message: ‘other’ is different type of Path.

References:

Share with the World!