gpt4 book ai didi

java - 读取jar中的文件

转载 作者:行者123 更新时间:2023-11-30 10:33:30 25 4
gpt4 key购买 nike

我正在尝试打开我的 jar 存档中的一个文件。

我使用这个 Maven 插件:

  <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.fatec.migration.script.utils.Script</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>assemble-all</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>

我构建然后复制我的存档:

cp /home/stephane/dev/java/projects/fatec/Fiabilisation_Controles_XP_AS/target/fatec-script-jar-with-dependencies.jar .

现在我可以尝试运行它了:

java -jar fatec-script-jar-with-dependencies.jar 1 2017-02-01 2017-02-02 all

唉,找不到文件了:

The file secure/extrapack-renew.sql could not be opened.
java.lang.NullPointerException
at com.fatec.migration.script.utils.AbstractScript.loadSqlStatement(AbstractScript.java:75)

但文件确实存在,我可以在存档中看到它:

$ jar -tvf target/fatec-script-jar-with-dependencies.jar | grep "secure/extrapack-renew.sql"
1844 Fri Feb 10 17:43:46 CET 2017 secure/extrapack-renew.sql

以下是我尝试打开文件的方式:

protected String loadSqlStatement(String scriptPath, String filename) {
String filepath = buildSqlFilePath(scriptPath, filename);
try {
return new String(Files.readAllBytes(Paths.get(getClass().getResource(filepath).toURI())));
} catch (Exception e) {
System.err.println("The file " + filepath + " could not be opened.");
e.printStackTrace();
}
return null;
}

private String buildSqlFilePath(String scriptPath, String filename) {
return scriptPath + "/" + filename;
}

scriptPath 是“secure”,文件名为“extrapack-renew.sql”。

我错过了什么?

最佳答案

我认为你的问题是你使用 getResource() 的方式:

Paths.get(getClass().getResource(filepath).toURI());

您使用相对类路径(相对于当前类位置)来检索“extrapack-renew.sql” 文件。
这意味着此资源必须位于要检索的 jar 中的此路径内。

如果资源不在当前类路径中,用于检索资源的路径应以“/”字符开头,以便指定资源的绝对名称:

Paths.get(getClass().getResource("/"+filepath).toURI());

当然如果你使用maven,extrapack-renew.sql应该在

源项目的 src/main/resources/secure 文件夹,以便 "/secure/extrapack-renew.sql" 成为类路径中的资源。

关于java - 读取jar中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42164921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com