Reputation: 2344
I am trying to create jar where I can read a config file outside the jar file. Preferably from the directory where the jar file is located. My directory structure is as follows:
/src/main/resources/config
I have a maven project that I run mvn install on to create a jar file.
<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>
Right now I am manually moving my config folder from /target/classes/config to /target/config I have researched the maven assembly plugin however I have tried all the different configurations of it and I was unable to get it to output only to /target/config it would always output /target/audit-1.0/config where audit-1.0 is my maven project name.
I am using Intellij IDEA to debug my program and to build/install the maven project.
In code I am trying to access the file via
InputStream stream = Class.class.getResourceAsStream("/config/config.xml");
Which works when I run it in the IDE however when I run it from the command line:
java -jar ./audit-1.0.jar
It throws an error after trying to access "inputStream":
Exception in thread "main" java.lang.NullPointerException
I understand that "/config/config.xml" should point to "/target/audit-1.0.jar!/config/config.xml". However, I would like it to point to "/target/config/config.xml"
Any ideas? Is this even possible?
Upvotes: 3
Views: 7057
Reputation: 510
File base = new File(<Current class name here>.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile();
File configFile= new File(base,"config.xml");
Upvotes: 3