Search code examples
javanio2

Using a java.nio.file.Path instance and a string to navigate to a sub-path


How can I use a java.nio.file.Path object to navigate to a sub-path?

I'd have thought that something like path = path.subFolder(string) would work where string specifies a sub-folder relative to the initial path.

But there doesn't seem to be such a method available.

Before "I go in and out of a string", I'd like to check if I've missed something.


Solution

  • You are looking for Path.resolve(other).

    Quoting its Javadoc:

    For example, suppose that the name separator is "/" and a path represents "foo/bar", then invoking this method with the path string "gus" will result in the Path "foo/bar/gus".

    Sample code:

    Path path = Paths.get("/foo/bar");
    Path subFolder = path.resolve("gus"); // represents the path "/foo/bar/gus"