从类路径加载配置文件

从类路径加载配置文件

本文介绍了从类路径加载配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

文件夹结构如下:

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

我无法终生访问配置.xml文件使用ClassLoader。它连同所有依赖项一起在清单文件的Class-Path条目中明确列出。

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

使用xmlName作为以下所有值的字符串:

With xmlName as a string of all the following values:

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

与此相关,我在config目录中也有一个log4j.properties文件。如何获取log4j来拾取它?其他参考资料指出,它只需要位于类路径中,并且也可以在jar的清单文件中明确命名。有人可以指出我正确的方向吗?

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?

更新:

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

Here are the actual entries from Class-Path:

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


推荐答案

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

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

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

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

这篇关于从类路径加载配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 09:36