2

I've now read numerous articles on the use of Java somePath.resolve( someOtherPath ) but I can't find a precise definition, with helpful examples, of what exactly "resolving" a Path means. Everyone seems to assume you know. Can someone define it non-circularly? Or point me to a (non-circular) explainer?

Robert Lewis
  • 1,847
  • 2
  • 18
  • 43

2 Answers2

2

The answer to this is defined in the documentation, which does a great job of indicating what the method does.

Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the resolve method. 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".

In other words, if the path C:/Program Files/Foo/ is the current Path and Bar exists in Foo, you could do the following:

Path parent = Paths.get("C:", "Program Files", "Foo");

Path child = parent.resolve("Bar");
Renis1235
  • 4,116
  • 3
  • 15
  • 27
Jason
  • 5,154
  • 2
  • 12
  • 22
  • 3
    Another circular definition that uses "resolve" to define "resolve". – Robert Lewis Apr 21 '21 at 03:06
  • The documentation says that if the string can't be converted to a path, then it throws an InvalidPathException. But under what circumstances can something not be converted? In this example, if Bar does not exist, does resolving it fail? Or does it create a Bar file? Or does it just return a path that points at a theoretical Bar file or directory that I would have to make real with another call? – Tim Nov 17 '21 at 18:52
  • 1
    That is a good question Tim. Path relies on FileSystem which is dependent on the OS, so the behaviour would depend on the OS (I presume). I don't believe Path is responsible for file or directory creation, but I could be wrong. That would be up to something like `Files#write(Path)` where if Bar didn't exist, it would create bar, based on potentially the `OpenOption`'s provided. I apologize if this wasn't helpful, took a quick glance at the implementation. – Jason Nov 17 '21 at 19:23
1

Jason's answer is complete, but on the off chance you're looking for an even simpler answer/example..

I would say the "resolve" method that you specificaly referred to (which starts at somePath) starts at a certain Path, somePath, and then tells you what would happen if you choose to go to someOtherPath but specifically starting at somePath.

So if you had a directory structure on a PC, for example, like this:

C:
 - FolderA
   - Folder1
 - FolderB
   - Folder1

If you resolved someOtherPath as "Folder1", then it would depend where you started...

  • If your somePath was "/FolderA" then you'd end up at "C:/FolderA/Folder1"
  • If your somePath was "/FolderB" then you'd end up at "C:/FolderB/Folder1"
  • If your somePath was "/" (the root), then you'd have an invalid path...
Atmas
  • 2,389
  • 5
  • 13