开发者

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

开发者 https://www.devze.com 2023-03-31 22:11 出处:网络
As开发者_开发知识库 per java.nio.file.Path: A relative path cannot be constructed if only one of the paths have a root component.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消