6

I wonder what's the difference between using Paths.get() and Path.resolve as in this example:

public static void main(String[] args) {
    Path p1 = Paths.get("dir1","dir2","file.jpg");
    Path p2 = Paths.get("").resolve("dir1/dir2/file.jpg");

    System.out.println(p1.toString()); // yields: dir1/dir2/file.jpg
    System.out.println(p2.toString()); // yields: dir1/dir2/file.jpg
}

It looks as if both behave identically, but in a Java EE application I witnessed that p1 got the home directory assigned as a prefix. I found @Aleksandr Dubinsky's answer to this StackOverflow question How to combine paths in Java?, but I don't understand the meaning of the cited javadoc:

Note that Paths.get() (as suggested by someone else) doesn't have an overload taking a Path, and doing Paths.get(path.toString(), childPath) is NOT the same thing as resolve(). From the Paths.get() docs:

Note that while this method is very convenient, using it will imply an assumed reference to the default FileSystem and limit the utility of the calling code. Hence it should not be used in library code intended for flexible reuse. A more flexible alternative is to use an existing Path instance as an anchor, such as:

Path dir = ...
Path path = dir.resolve("file");

Specifically, I don't understand what the javadoc wants to say with "will imply an assumed reference to the default FileSystem."

Fabian K
  • 141
  • 1
  • 7
  • Seems you don't understand what a [`FileSystem`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html) is, so maybe you should read up on that first. If you don't understand what a file system is, and how there can be more than one file system, the distinction mentioned in the quoted text will be meaningless to you. – Andreas Feb 22 '19 at 21:37

1 Answers1

3

Paths.get(...) in a way works like Python's os.path.join(...) function by simply connecting parts of path using an appropriate file separator. The resolve method has some internal logic and assumptions about the arguments. The use of actual file system means that this method will e.g. check if the argument is an absolute path. The resolve method in general case will use some specific file system, while get will be backed by a "default file system".

Compare:

jshell> Paths.get("one", "/two")
$6 ==> one/two
jshell> Paths.get("one").resolve("/two")
$7 ==> /two 
scrutari
  • 1,378
  • 2
  • 17
  • 33
  • 1
    In my case I had used Path.resolve in a test with JUnit5 @TempDir, to generate file in a temporary directory and the test worked very fine on Windows but on Unix it didn't work it returns an exception java.nio.file.NoSuchFileException, reading this question/answer I did change all Path.resolve() to Paths.get() and it did work in both enviroments ! – S_intg Feb 16 '22 at 09:43