Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a configuration file from the classpath

Tags:

java

classpath

I'm working on making my Java app easy to deploy to other computers and am writing an ant script to do so, that is going fine.

I'm having trouble loading resources that are listed in the classpath named in the manifest file of the jar.

Folder structure looks like this:

/MyProgram.jar
/lib/<dependencies>
/config/configuration.xml

I can not for the life of me access the configuration.xml file using the ClassLoader. It, along with all the dependencies are listed explicitly in the Class-Path entry to the manifest file.

I've tried many variants of the following:

this.xml = Thread.currentThread().getContextClassLoader()
                 .getResourceAsStream(xmlName);

this.xml = this.getClass().getResourceAsStream(xmlName);

With xmlName as a string of all the following values:

"config/configuration.xml"
"configuration.xml"
"config.configuration.xml"

Related to this, I also have a log4j.properties file in the config directory. How do I get log4j to pick it up? Other references say it just needs to be in the classpath, and it too is explicitly named in the jar's manifest file. Can someone point me in the right direction?

Update:

Here are the actual entries from Class-Path:

Class-Path: <snip dependencies> config/configuration.xml config/log4j.properties
like image 880
Collin Avatar asked Dec 02 '22 03:12

Collin


1 Answers

Classpath entries should either be directories or jar files, not individual files. Try changing your classpath to point to the config directory instead of the individual config files.

this.xml = Thread.currentThread().getContextClassLoader()
             .getResourceAsStream("config.xml");

Better yet would be to just include your config directory in MyProgram.jar. This would prevent you from needing to add it specifically to the classpath.

this.xml = Thread.currentThread().getContextClassLoader()
             .getResourceAsStream("/config/configuration.xml");
like image 93
gcooney Avatar answered Dec 21 '22 17:12

gcooney