当我尝试相对于另一个路径相对于另一个路径时,为什么会获得ProviderMismatchException? [英] Why do I get ProviderMismatchException when I try to .relativize() a Path against another Path?

查看:65
本文介绍了当我尝试相对于另一个路径相对于另一个路径时,为什么会获得ProviderMismatchException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[注:自我回答的问题]

[note: self answered question]

我已经使用java.nio打开了一个 FileSystem 到一个zip文件.我已经从该文件系统中获得了 Path :

I have opened a FileSystem to a zip file using java.nio. I have gotten a Path from that filesystem:

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

现在我在本地文件系统上有一个目录,该目录是通过以下方式获得的:

Now I have a directory on the local filesystem which I have obtained using:

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

我想测试/local/dir/path/into/zip 是否存在,所以我使用以下命令检查其存在:

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

Files.exists(localDir.resolve(zipPath))

但是我得到一个 ProviderMismatchException .为什么?我该如何解决?

but I get a ProviderMismatchException. Why? How do I fix this?

推荐答案

此行为已记录在案,尽管它不是很明显.您必须深入研究 java.nio.file 包描述,在最后看到:

This behaviour is documented, albeit it is not very visible. You have to delve into the java.nio.file package description to see, right at the end, that:

除非另有说明,否则使用一个参数(由另一个提供程序创建的对象)调用由一个提供程序创建的此程序包中任何类或接口的方法,都会引发ProviderMismatchException.

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

这种行为的原因可能并不明显,但请考虑例如两个文件系统可以定义

The reasons for this behaviour may not be obvious, but consider for instance that two filesystems can define a different separator.

JDK中没有任何方法可以帮助您.如果您的文件系统使用相同的分隔符,则可以使用以下方法解决此问题:

There is no method in the JDK which will help you there. If your filesystems use the same separator then you can work around this using:

path1.resolve(path2.toString())

否则,该实用程序方法可以提供帮助:

Otherwise this utility method can 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));

这篇关于当我尝试相对于另一个路径相对于另一个路径时,为什么会获得ProviderMismatchException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆