我在 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: 找不到提供程序
有趣的是,该代码适用于默认FileSystem
。
- 此错误是什么意思?
- 我应该如何创建我的 Zip
FileSystem
?
在 JDK 12 之前,通过该特定构造函数不支持此操作(Path, ClassLoader
(
此问题已在 JDK12 中修复,提交 196c20c0d14d99cc08fae64a74c802b061231a41
有问题的代码位于 JDK 11 及更早版本的 ZipFileSystemProvider 中:
if (path.getFileSystem() != FileSystems.getDefault()) {
throw new UnsupportedOperationException();
}
这有效,但它似乎很笨拙,而且至关重要的是我不确定它为什么有效。
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"扩展名以外的其他扩展名。