我正在尝试创建 jar,我可以在其中读取 jar 文件之外的配置文件。最好从 jar 文件所在的目录。我的目录结构如下:
/src/main/resources/config
我有一个 maven 项目,我在上面运行 mvn install 来创建一个 jar 文件。
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.expedia.e3.qm.perforce.audit.Main</mainClass>
</manifest>
<manifestEntries>
<Class-Path>config/config.xml</Class-Path>
</manifestEntries>
</archive>
<excludes>
<exclude>**/config/</exclude>
</excludes>
</configuration>
</plugin>
现在我正在手动将我的配置文件夹从/target/classes/config 移动到/target/config 我已经研究了 maven 程序集插件但是我已经尝试了它的所有不同配置但我无法让它输出仅对/target/config 它总是输出/target/audit-1.0/config 其中 audit-1.0 是我的 maven 项目名称。
我正在使用 Intellij IDEA 调试我的程序并构建/安装 maven 项目。
在代码中,我试图通过
访问文件InputStream stream = Class.class.getResourceAsStream("/config/config.xml");
当我在 IDE 中运行它时有效,但是当我从命令行运行它时:
java -jar ./audit-1.0.jar
尝试访问“inputStream”后抛出错误:
Exception in thread "main" java.lang.NullPointerException
我知道“/config/config.xml”应该指向“/target/audit-1.0.jar!/config/config.xml”。但是,我希望它指向“/target/config/config.xml”
有什么想法吗?这可能吗?
最佳答案
File base = new File(<Current class name here>.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile();
File configFile= new File(base,"config.xml");
关于java - 读取jar外的配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14490960/