Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

java - Loading a configuration file from the 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...