Andy Thomas Andy Thomas - 1 year ago 87
Java Question

Test whether Path.relativize() would succeed?

The method

will throw
with some arguments.

A relative path cannot be constructed if only one of the paths have a root component. Where both paths have a root component then it is implementation dependent if a relative path can be constructed.

For example, on Windows, the method can fail if the two arguments refer to paths on different drives.

Is there an OS-neutral way to test whether a particular argument is legal, before calling
, to avoid relying on an exception to handle a non-exceptional case?

Answer Source

It says it is "implementation dependent", so no, but making some assumptions, you can check if they share the same root and file system.

getRoot() returns null if the path has no root component, otherwise / for Linux-like OS's and e.g. C:\ for Windows. If the other path has a different root (e.g. D:\), then relativize() will fail.

So, if both Path objects are for the same FileSystem, and both are either relative (getRoot() returns null), or both have the same root component, relativize() should work fine.

Not perfect solution, since we don't know what the "implementation" thinks, but close enough?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download