如何引用可执行 jar 和 Eclipse 中的属性文件?

发布于 2024-12-08 16:57:59 字数 642 浏览 3 评论 0原文

我使用两个属性文件:log4j.propertiesmyapp.properties。当我在 Eclipse 和可执行 jar 中执行应用程序时,我想正确加载它们。

ATM 文件存储在此处:/src/configs/*.properties。我在代码中使用以下行引用它们:

config = new PropertiesConfiguration(getClass().getResource("/configs/myapp.properties"));

如果我在 Eclipse 中执行我的应用程序,这会很好用,但如果我执行(从 eclipse 生成的)可执行 jar,则会失败。我已经在 /META-INF/ 中创建了一个清单文件,并将这一行写入其中:

Class-Path: .

Toeffect,executing the jar still Failure :-(Where do I have to put myproperties files and how do I必须引用它们吗?

如果我在 Eclipse 中执行 jar,是否也可以在 jar 外部引用它们? 谢谢你!

I use two properties files: log4j.properties and myapp.properties. I want to load them correctly when I execute my application in Eclipse AND in an executable jar.

ATM the files are stored here: /src/configs/*.properties. I reference them in my code with this line:

config = new PropertiesConfiguration(getClass().getResource("/configs/myapp.properties"));

This works great if I execute my application in Eclipse, but fails if I execute the (from eclipse generated) executable jar. I have created a manifest file in /META-INF/ and wrote this line into it:

Class-Path: .

To effect, executing the jar still fails :-( Where do I have to put my properties files and how do I have to reference them?

Is it also possible to reference them outside the jar if I execute the jar and inside my project if I'm in Eclipse?
Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不可一世的女人 2024-12-15 16:57:59

您尝试加载属性文件的方式对我来说看起来不错。您是否检查过属性文件是否确实是生成的 jar 文件的一部分?

The way you try to load the properties file looks fine to me. Have you checked if the properties files are actually part of the generated jar file?

╰沐子 2024-12-15 16:57:59

通常属性文件是为了在不重建 jar 的情况下部署/修改,例如环境/外部资源特定的东西,因此它们是单独存储的。

但如果您需要将它们保留在内部,请确保(在您的情况下)“configs/myapp.properties”实际上位于 JAR 的根级别。只需解压您创建的 jar 即可查看其中有什么。或者您可以运行:

jar -tvf your.jar | grep myapp.properties

查看 JAR 中的实际路径,而无需解压它。

如果存在,您可以通过类加载器加载它们,如下所示:

ClassLoader cl = YourClass.class.getClassLoader()

config = new PropertiesConfiguration( cl.getResourceAsStream( "configs/myapp.properties" ) ) );

Usually property files are meant to be deployed / modified without rebuilding the jar, e.g. environment / external resource specific things, hence they are stored separately.

But in case you have a need to keep them inside, make sure that (in your case) "configs/myapp.properties" are actually at the JAR's root level. Just unjar that jar you created to see what is there. Or you can run:

jar -tvf your.jar | grep myapp.properties

to see the actual path within a JAR without unjaring it.

If it is there, you can load them via a classloader as follows:

ClassLoader cl = YourClass.class.getClassLoader()

config = new PropertiesConfiguration( cl.getResourceAsStream( "configs/myapp.properties" ) ) );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文