Reading config file outside of jar

I am trying to create a jar where I can read the config file outside of the jar file. Preferably from the directory where the jar file is located. My directory structure looks like this:

/src/main/resources/config

      

I have a maven project in which I run mvn install to generate 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 researched the maven build plugin but I tried all different configurations and I couldn't get it to output only for / target / config it always outputs / target / audit -1.0 / config where audit-1.0 is my maven project name.

I am using Intellij IDEA to debug my program and build / install a maven project.

In the code, I am trying to access a file via

InputStream stream = Class.class.getResourceAsStream("/config/config.xml");

      

Which works when I run it in the IDE, but 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 it possible?

+3


source to share


1 answer


File base = new File(<Current class name here>.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile();
File configFile= new File(base,"config.xml");

      



+3


source







All Articles