I am trying to familiarize myself with java.nio.file.Path.relativize() to no avail.
I have read the javadocs, and I have seen examples. However, I still cannot get my head around the following example(I use Linux, apologies to window users):
Working directory for program is: /home/userspace/workspace/java8.
With two files: /home/userspace/workspace/java8/zoo.txt and /home/userspace/temp/delete/dictionary.txt
The following program calls Path.relativize():
package certExam.java8.ch9NIO.paths;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Relativize
{
public static void main(String[] args)
{
Path relativePathToZoo = Paths.get("zoo.txt");
Path relativePathToDictionary = Paths.get("../../temp/delete/dictionary.txt");
System.out.println("relativePathToZoo.relativize(relativePathToDictionary): "+relativePathToZoo.relativize(relativePathToDictionary));
System.out.println("relativePathToZoo.relativize(relativePathToDictionary).toAbsolutePath(): "+relativePathToZoo.relativize(relativePathToDictionary).toAbsolutePath());
System.out.println("relativePathToZoo.relativize(relativePathToDictionary).toAbsolutePath().normalize(): "+relativePathToZoo.relativize(relativePathToDictionary).toAbsolutePath().normalize());
System.out.println("relativePathToDictionary.relativize(relativePathToZoo): "+relativePathToDictionary.relativize(relativePathToZoo));
System.out.println("relativePathToDictionary.relativize(relativePathToZoo).toAbsolutePath().normalize(): "+relativePathToDictionary.relativize(relativePathToZoo).toAbsolutePath().normalize());
System.out.println();
}
}
The output is:
relativePathToZoo.relativize(relativePathToDictionary): ../../../temp/delete/dictionary.txt
relativePathToZoo.relativize(relativePathToDictionary).toAbsolutePath(): /home/userspace/workspace/java8/../../../temp/delete/dictionary.txt
relativePathToZoo.relativize(relativePathToDictionary).toAbsolutePath().normalize(): /home/temp/delete/dictionary.txt
relativePathToDictionary.relativize(relativePathToZoo): ../../../../../zoo.txt
relativePathToDictionary.relativize(relativePathToZoo).toAbsolutePath().normalize(): /zoo.txt
My question, the bit I cannot understand is: Why does relativePathToDictionary.relativize(relativePathToZoo) output ../../../../../zoo.txt?
When normalized, it would make you think that zoo.txt lives in the root directory.
How does relativize() work out such a deep path? I understand that relativize() works in relation to the current working directory, so it adds .. to every path. But I am cannot understand, how it worked out the path to zoo.txt in relation to dictionary.txt.