为我的 zip 创建文件系统时提供程序未发现异常?
Provider not found exception when creating a FileSystem for my zip?
我在 JimFS FileSystem
实例上创建了一个 Zip 文件。我现在想使用 Java FileSystem
API 阅读 Zip。
下面是我如何创建 FileSystem
:
final FileSystem zipFs = FileSystems.newFileSystem(
source, // source is a Path tied to my JimFS FileSystem
null);
但是,这会引发错误:
java.nio.file.ProviderNotFoundException: Provider not found
有趣的是,代码使用默认 FileSystem
。
- 这个错误是什么意思?
- 我应该如何创建 Zip
FileSystem
?
这行得通,但它看起来很老套,关键是我不确定为什么它行得通。
public static FileSystem fileSystemForZip(final Path pathToZip) {
Objects.requireNotNull(pathToZip, "pathToZip is null");
try {
return FileSystems.getFileSystem(pathToZipFile.toUri());
} catch (Exception e) {
try {
return FileSystems.getFileSystem(URI.create("jar:" + pathToZipFile.toUri()));
} catch (Exception e2) {
return FileSystems.newFileSystem(
URI.create("jar:" + pathToZipFile.toUri()),
new HashMap<>());
}
}
}
检查 source
路径是否指向 zip 存档文件。
在我的例子中,它指向普通的文本文件,它的扩展名甚至不是“.zip”。
在 JDK 12 之前通过特定构造函数 (Path, ClassLoader
)
不支持此功能
这已在 JDK12 中修复,提交 196c20c0d14d99cc08fae64a74c802b061231a41
违规代码位于 JDK 11 及更早版本的 ZipFileSystemProvider 中:
if (path.getFileSystem() != FileSystems.getDefault()) {
throw new UnsupportedOperationException();
}
我在 JimFS FileSystem
实例上创建了一个 Zip 文件。我现在想使用 Java FileSystem
API 阅读 Zip。
下面是我如何创建 FileSystem
:
final FileSystem zipFs = FileSystems.newFileSystem(
source, // source is a Path tied to my JimFS FileSystem
null);
但是,这会引发错误:
java.nio.file.ProviderNotFoundException: Provider not found
有趣的是,代码使用默认 FileSystem
。
- 这个错误是什么意思?
- 我应该如何创建 Zip
FileSystem
?
这行得通,但它看起来很老套,关键是我不确定为什么它行得通。
public static FileSystem fileSystemForZip(final Path pathToZip) {
Objects.requireNotNull(pathToZip, "pathToZip is null");
try {
return FileSystems.getFileSystem(pathToZipFile.toUri());
} catch (Exception e) {
try {
return FileSystems.getFileSystem(URI.create("jar:" + pathToZipFile.toUri()));
} catch (Exception e2) {
return FileSystems.newFileSystem(
URI.create("jar:" + pathToZipFile.toUri()),
new HashMap<>());
}
}
}
检查 source
路径是否指向 zip 存档文件。
在我的例子中,它指向普通的文本文件,它的扩展名甚至不是“.zip”。
在 JDK 12 之前通过特定构造函数 (Path, ClassLoader
)
这已在 JDK12 中修复,提交 196c20c0d14d99cc08fae64a74c802b061231a41
违规代码位于 JDK 11 及更早版本的 ZipFileSystemProvider 中:
if (path.getFileSystem() != FileSystems.getDefault()) {
throw new UnsupportedOperationException();
}