With Java NIO Path objects:
b
and a relative path r
, to get the full path f
I can call b.resolve(r)
.f
and the base path b
, to get the relative path r
I can call b.relativize(f)
.f
and r
, and want to find b
?Looking over the Path
API, I can't see any simple/straightforward solution. The best I've been able to come up with is to simultaneously iterate over getParent()
for both f
and r
until r'
is empty/null, then f'
should be b
. But that seems clunky and inefficient.
I also tried a solution based on f.subpath()
but that method strips the root component (e.g. C:\
).
To retrieve the base path, you can use subpath()
by passing as begin index 0
and as end index the difference of path elements between the full path and the relative path, that is fullPath.getNameCount() - relativePath.getNameCount()
For example :
Path fullPath = Paths.get("C:/folder1/folder2/a/b/c.txt");
Path relativePath = Paths.get("b/c.txt");
Path basePath = fullPath.getRoot().resolve(fullPath.subpath(0, fullPath.getNameCount() - relativePath.getNameCount()));
System.out.println("basePath=" + basePath);
output :
basePath=C:\folder1\folder2\a
Note that fullPath.getRoot().resolve()
is required because Windows doesn't consider a token with :
as a path element in its subpath()
implementation.
So in the actual example, C:\
will never be returned by subpath()
.
C:\
is considered in the Windows implementation as the root
component.
As a general note, even if our application run on an Unix based OS, we should keep it to be not OS dependent. The OS where the JVM runs may be different in the future.