简体   繁体   中英

How to reference properties files in executable jar AND Eclipse?

I use two properties files: log4j.properties and myapp.properties . I want to load them correctly when I execute my application in Eclipse AND in an executable jar.

ATM the files are stored here: /src/configs/*.properties . I reference them in my code with this line:

config = new PropertiesConfiguration(getClass().getResource("/configs/myapp.properties"));

This works great if I execute my application in Eclipse, but fails if I execute the (from eclipse generated) executable jar. I have created a manifest file in /META-INF/ and wrote this line into it:

Class-Path: .

To effect, executing the jar still fails :-( Where do I have to put my properties files and how do I have to reference them?

Is it also possible to reference them outside the jar if I execute the jar and inside my project if I'm in Eclipse? Thank you!

The way you try to load the properties file looks fine to me. Have you checked if the properties files are actually part of the generated jar file?

Usually property files are meant to be deployed / modified without rebuilding the jar, eg environment / external resource specific things, hence they are stored separately.

But in case you have a need to keep them inside, make sure that (in your case) "configs/myapp.properties" are actually at the JAR's root level. Just unjar that jar you created to see what is there. Or you can run:

jar -tvf your.jar | grep myapp.properties

to see the actual path within a JAR without unjaring it.

If it is there, you can load them via a classloader as follows:

ClassLoader cl = YourClass.class.getClassLoader()

config = new PropertiesConfiguration( cl.getResourceAsStream( "configs/myapp.properties" ) ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM