Why am I getting a ProviderMismatchException when I try to .relativize () a path to another path?

[note: the answer to the question itself]

I opened a FileSystem file for a zip file using java.nio. I got Path from this file system:

 final Path zipPath = zipfs.getPath("path/into/zip"); 

Now I have a directory in the local file system, which I got with:

 final Path localDir = Paths.get("/local/dir") 

I want to check if /local/dir/path/into/zip exists, so I check its existence using:

 Files.exists(localDir.resolve(zipPath)) 

but I get a ProviderMismatchException . What for? How to fix it?

+7
java java-7
source share
1 answer

This behavior is documented, although it is not very noticeable. You must delve into the description of java.nio.file in order to see, in the end, that:

Unless otherwise specified, a method call of any class or interface in this package created by one provider with a parameter that is an object created by another provider will raise a ProviderMismatchException.

The reasons for this behavior may not be obvious, but consider, for example, that two file systems can define a different delimiter .

There is no method in the JDK that will help you there. If your file systems use the same delimiter, you can work around this using:

 path1.resolve(path2.toString()) 

Otherwise, this utility method may help:

 public static Path pathTransform(final FileSystem fs, final Path path) { Path ret = fs.getPath(path.isAbsolute() ? fs.getSeparator() : ""); for (final Path component: path) ret = ret.resolve(component.getFileName().toString()); return ret; } 

Then the above can be written as:

 final Path localPath = pathTransform(localDir.getFileSystem(), zipPath); Files.exists(localDir.resolve(localPath)); 
+8
source share

All Articles