从 ZipFileSystem获取 FileSystemNotFoundException 在创建资源路径时提供

2022-08-31 19:47:19

我有一个Maven项目,在一个方法中,我想为我的资源文件夹中的目录创建一个路径。这是这样完成的:

try {
    final URI uri = getClass().getResource("/my-folder").toURI();
    Path myFolderPath = Paths.get(uri);
} catch (final URISyntaxException e) {
    ...
}

生成的看起来像 。URIjar:file:/C:/path/to/my/project.jar!/my-folder

堆栈跟踪如下所示:

Exception in thread "pool-4-thread-1" java.nio.file.FileSystemNotFoundException
    at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171)
    at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
    at java.nio.file.Paths.get(Paths.java:143)

这似乎是有效的。前面的部分指向生成的 jar 文件,其后面的部分指向存档的根目录中。我之前已使用此说明创建指向我的资源的路径。为什么我现在有异常?URI!my-folder


答案 1

您需要先创建文件系统,然后才能访问 zip 中的路径,例如

final URI uri = getClass().getResource("/my-folder").toURI();
Map<String, String> env = new HashMap<>(); 
env.put("create", "true");
FileSystem zipfs = FileSystems.newFileSystem(uri, env);
Path myFolderPath = Paths.get(uri);

此操作不会自动完成。

查看 http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html


答案 2

如果您打算读取资源文件,可以直接使用 。这将直接设置文件系统。如果找不到您的资源,该函数将返回,否则您将直接拥有一个输入流来解析您的资源。getClass.getResourceAsStreamnull


推荐