132. Constructing a path between two locations

Constructing a relative path between two locations is a job for the Path.relativize() method.

Basically, the resulted relative path (returned by Path.relativize()) starts from a path and ends on another path. This is a powerful feature that allows us to navigate between different locations using relative paths that are resolved against the previous paths.

Let's consider the following two paths:

Path path1 = Paths.get("JBossTools3.pdf");
Path path2 = Paths.get("JavaModernChallenge.pdf");

Notice that JBossTools3.pdf and JavaModernChallenge.pdf are siblings. This means that we can navigate from one to another by going up one level and then down one level. This navigation case is revealed by the following examples as well:

// ..JavaModernChallenge.pdf
Path path1ToPath2 = path1.relativize(path2);

// ..JBossTools3.pdf
Path path2ToPath1 = path2.relativize(path1);

Another common case involves a common root element:

Path path3 = Paths.get("/learning/packt/2003/JBossTools3.pdf");
Path path4 = Paths.get("/learning/packt/2019");

So, path3 and path4 share the same common root element, /learning. For navigating from path3 to path4, we need to go up two levels and down one level. In addition, for navigating from path4 to path3, we need to go up one level and down two levels. Check out the following code:

// ....2019
Path path3ToPath4 = path3.relativize(path4);

// ..2003JBossTools3.pdf
Path path4ToPath3 = path4.relativize(path3);
Both paths must include a root element. Accomplishing this requirement does not guarantee success because the construction of the relative path is implementation-dependent.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset