我需要打开一个位于 maven jar 包中的文件。它是我使用的框架的模型配置,库类的构造函数需要传递 File 类型的对象。我可以毫无问题地使用类加载器获取配置文件的路径。但是——不幸的是——File 无法读取 jar 中的文件。所以我得到 java.io.FileNotFoundException。现在我正在寻找解决这个问题的方法。我的计划是解压模型配置文件并将其放在一个临时目录中。但是,在开始编码之前,我想了解是否有任何其他解决方案可以解决像我这样的问题。
更新:我需要在运行时读取一个文件。
请您参考如下方法:
如果您是从 Maven 构建中执行此操作,请使用
将 jar 资源解压缩到文件中dependency:unpack-dependencies
(如果 jar 是项目的 Maven 依赖项之一)<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>unpack-dependencies</id> <phase>generate-resources</phase> <goals> <goal>unpack-dependencies</goal> </goals> <configuration> <includeGroupIds>the.groupId</includeGroupIds> <includeArtifactIds>the.artifactId</includeArtifactIds> <includes>**/path/to/your/resource.txt</includes> <outputDirectory>where/do/you/want/it</outputDirectory> </configuration> </execution> </executions> </plugin>
或使用
dependency:unpack
(如果 jar 没有依赖项,但仍然可以作为 maven Artifact 使用)<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>unpack</id> <phase>generate-resources</phase> <goals> <goal>unpack</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>the.groupid</groupId> <artifactId>the.artifactid</artifactId> <version>the.version</version> <type>jar</type> <outputDirectory>where/do/you/want/it</outputDirectory> <includes>**/path/to/your/resource.txt</includes> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin>