繁体   English   中英

从类路径加载配置文件

[英]Loading a configuration file from the classpath

我正在努力使我的Java应用程序易于部署到其他计算机,我正在写一个蚂蚁脚本来做到这一点,这很好。

我在加载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

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

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

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

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

据我所知,log4j.xml应该在你的类路径的根目录。

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

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

启动应用程序时,可以使用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文件中?

关于log4j:如果你想让它使用默认的不同配置文件,你可以使用

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

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

还有

org.apache.log4j.xml.DOMConfigurator

对于XML文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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