Search code examples
javapathnio

Java NIO Paths: getting the base path from a full path?


With Java NIO Path objects:

  • If I have a base path b and a relative path r, to get the full path f I can call b.resolve(r).
  • If I have the full path f and the base path b, to get the relative path r I can call b.relativize(f).
  • But what can I do if I have 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:\).


Solution

  • To retrieve the base path, you can use subpath() by passing as begin index 0and 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.