从类路径加载配置文件

时间:2011-01-27 20:44:39

标签: java classpath

我正在努力使我的Java应用程序易于部署到其他计算机,并且正在编写一个ant脚本来实现这一目标,这很好。

我无法加载jar中清单文件中指定的类路径中列出的资源。

文件夹结构如下所示:

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

我不能为我的生活使用ClassLoader访问configuration.xml文件。它与所有依赖项一起在清单文件的Class-Path条目中明确列出。

我尝试了以下许多变体:

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

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

将xmlName作为包含以下所有值的字符串:

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

与此相关,我在config目录中也有一个log4j.properties文件。我如何让log4j拿起它?其他引用说它只需要在类路径中,它也在jar的manifest文件中明确命名。有人能指出我正确的方向吗?

更新

以下是Class-Path中的实际条目:

Class-Path: <snip dependencies> config/configuration.xml config/log4j.properties

4 个答案:

答案 0 :(得分:13)

类路径条目应该是目录或jar文件,而不是单个文件。尝试更改类路径以指向config目录而不是单个配置文件。

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

最好还是将您的配置目录包含在MyProgram.jar中。这样可以防止您需要将其专门添加到类路径中。

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

答案 1 :(得分:3)

据我所知,log4j.xml应该位于类路径的根目录..

此外,您可以使用以下代码脚本读取配置文件。和config目录应该在你的classpath。

this.xml = this.getClass().getResourceAsStream("/config/configuration.xml"); 

答案 2 :(得分:1)

启动应用程序时可以使用log4j.configuration系统属性:

java -Dlog4j.configuration=config/log4j.properties MyApp

请参阅“默认初始化过程”下的http://logging.apache.org/log4j/1.2/manual.html

关于未选择的其他配置文件,您的Manifest.mf文件是什么样的?你在使用像

这样的东西吗?
Class-Path: config/configuration.xml lib/yourLibOne.jar lib/blah.jar
你的Manifest.mf文件中的

答案 3 :(得分:0)

关于log4j:如果您希望它使用默认的其他配置文件,您可以使用

org.apache.log4j.PropertyConfigurator.configure(...)

此静态方法的变体接受URL,属性或文件名。

还有

org.apache.log4j.xml.DOMConfigurator

表示XML文件。

相关问题