As per java.nio.file.Path
:
A relative path cannot be constructed if only one of the paths have a root component.
Why is this so? Why is it not possible to relativize like so:
Path path1 = Paths.get("/home/test");
Path path2 = Paths.get("home");
// throws an IllegalArgumentException
Path path3 = path1.relativize(path2);
I had imagined that path3
would result in the relative path ../
. Why is it valid for Path
to return a result that suggests that two directories sit at the same level within the file system if no root elements are defined, yet, when only one path defines a root element (as shown above), no relative path can be determined?
i.e.
Path path1 = Paths.get("home/test");
Path path2 = Paths.get("user");
// results in ../../user
Path path3 = path1.relativize(path2);
A non-absolute path is relative to some unspecified base directory. If you have two such paths, it will make some sense to imagine they are relative to the same (but still unspecified) base directory, and then it makes meaning to ask where one is with respect to the other.
On the other hand, if you have two paths of which only one is absolute, such as /home/test
and home
there is no knowing what there relation is. For example if the base directory happens to be /home/test/blah
, then home
means /home/test/blah/home
and it should therefore relativize to blah/home
. But how would the method know how to invent blah
(or to invent something else entirely)?
The whole point of using a relative path is to say, I'm not telling you yet what the base directory for this pathname is going to be. Expecting the runtime library to guess the base path that we're explicitly not telling it would be completely counter to that semantics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With