Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...