我正试图打开一个坐在我的jar文件中的文件。在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是“安全”和文件名是“extrapack-renew.sql”。
我错过了什么?
SQL文件位于jar文件中。它不应该被移动或改变。假设它是硬编码的。也许我不需要将它放在外部文件中,更不用说放在资源文件中。 – Stephane
事实上,如果你没有要求在jar被打包后改变它,你没有义务从jar中移出文件。这是一个部署选择。 – davidxxx