Where to use resolve() and relativize() method of java.nio.file.Path class?

I cannot understand how resolve() and relativize() method works?

Path resolve(Path) resolves the given path against this path.
Path relativize(Path) constructs a relative path of the given path against this path .
These are reverse operations.


Path resolve(Path other)

In the general use case of resolve(), you want to return a new Path object where you will join this Path object to the Path parameter that is a relative Path such as :

Path p1 = Paths.get("/Users/jack");
Path p2 = Paths.get("text1.txt");
Path result1 = p1.resolve(p2);

Here result1 will be the path join of p1 and p2, that is : /Users/jack/text1.txt.

In your example the parameter passed to the method is not a relative Path but an absolute :

Path p1 = Paths.get("/Users/jack/Documents/text1.txt");
Path p2 = Paths.get("/Users/jack/text2.txt");
Path result1 = p1.resolve(p2); 

It makes no sense to "append" a Path to another if the second is an absolute Path.
So the javadoc considers that in this case the parameter is returned as result of resolve() :

If the other parameter is an absolute path then this method trivially returns other.

Path relativize(Path other)

The doc says more specifically :

This method attempts to construct a relative path that when resolved against this path, yields a path that locates the same file as the given path.

It means that the returned Path is the relative path of the Path parameter relatively to this Path.

For example, if this path is "/a/b" and the given path is "/a/b/c/d" then the resulting relative path would be "c/d".

We will check that with your example :

Path p1 = Paths.get("/Users/jack/Documents/text1.txt");
Path p2 = Paths.get("/Users/jack/text2.txt");
Path result2 = p1.relativize(p2);   
// result2= ../../text2.txt

The ../../text2.txt Path is expected as result as the relative path produced ( ../../text2.txt) resolved against this path (/Users/jack/Documents/text1.txt) yields a path that locates the same file as the given path (/Users/jack/text2.txt) :

Paths.of("/Users/jack/Documents/text1.txt").resolve("../../text2.txt")

returns -> /Users/jack/text2.txt

resolve(): Joins two paths.

relativize (): construct a path from one location in the file system to another location.

Output explanation:

result1: /Users/jack/text2.txt: because you passed in an absolute path, resolve() returns the passed in the path as is if it is an absolute path.

result2: ../../text2.txt: to get to /Users/jack/text2.txt from /Users/jack/Documents/text1.txt" you need to to go two levels up, and then just select `text2.txt file.

Tags:

Java

Path

Resolve