Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't Java 7's new Path object relativize when only one Path includes a root element?

Tags:

java

java-7

nio

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);
like image 782
wulfgarpro Avatar asked Aug 30 '11 10:08

wulfgarpro


1 Answers

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.

like image 55
hmakholm left over Monica Avatar answered Sep 29 '22 07:09

hmakholm left over Monica