Why is Java 7 a new Path object not relativized when only one path contains a root element?

By java.nio.file.Path :

A relative path cannot be built if only one of the paths has a root component.

Why is this so? Why so relativization is impossible:

 Path path1 = Paths.get("/home/test"); Path path2 = Paths.get("home"); // throws an IllegalArgumentException Path path3 = path1.relativize(path2); 

I assumed that path3 will lead to a relative path ../ . Why is it permissible for Path return a result that assumes that two directories are at the same level in the file system if root elements are not defined, but when only one path defines the root element (as shown above), is it not possible to determine the relative path?

i.e.

 Path path1 = Paths.get("home/test"); Path path2 = Paths.get("user"); // results in ../../user Path path3 = path1.relativize(path2); 
+4
source share
1 answer

A non-absolute path refers to some unspecified base directory. If you have two such paths, it makes sense to assume that they belong to the same (but still unspecified) base directory, and then it makes sense to ask where it belongs to the other.

On the other hand, if you have two paths, of which only one is absolute, for example /home/test and home , it is not known what the relation is. For example, if the base directory is /home/test/blah , then home means /home/test/blah/home , and therefore it should refer to blah/home . But how would a method know how to invent blah (or invent something else completely)?

The whole point of using a relative path is to say that I am not yet telling you what the base directory for this path will be. Expecting the runtime library to guess the base path, which we are not explicitly talking about, completely contradicts this semantics.

+5
source

Source: https://habr.com/ru/post/1369632/


All Articles