简体   繁体   English

如何加载jar文件中的属性文件

[英]How to load property file located inside jar file

How to load property files placed in resource folder of an executable jar file. 如何加载放置在可执行jar文件的资源文件夹中的属性文件。 Here my app itself is a jar and it executes on it own. 在这里,我的应用程序本身就是一个jar,它自己执行。 It need to find this property file (placed within itself under resource folder) at runtime depending on the path mentioned in the code. 它需要在运行时根据代码中提到的路径找到此属性文件(放置在资源文件夹下的自身中)。 I have used below two methods but it didn't help me. 我使用了以下两种方法,但并没有帮助我。 Point here is, both these options are working fine when i execute in eclipse, but doesn't work when I pack it into an executable jar. 这里的要点是,当我在eclipse中执行时,这两个选项都可以正常工作,但是当我将其打包到可执行jar中时,这两个选项将不起作用。 It throws NullPointerException. 它抛出NullPointerException。 Only problem I see here is that jar is not able to pick the property files with given path. 我在这里看到的唯一问题是jar无法选择具有给定路径的属性文件。 Any help would be appreciated. 任何帮助,将不胜感激。

Method 1: Using Apache Commons Configuration 方法1:使用Apache Commons配置

 URL propFileURL = XYZ.class.getClassLoader().getResource("/config.properties");
Configuration propertyConfiguration = null;             
propertyConfiguration = new PropertiesConfiguration(propFileURL);

In above case I'm getting ConfigurationException. 在上述情况下,我正在获取ConfigurationException。 Class is not able to find file mentioned in given path. 类无法找到给定路径中提到的文件。

Method 2: Using getResourceAsStream. 方法2:使用getResourceAsStream。 I know that getResource doesn't work if we are to load files from network on in any other location. 我知道,如果我们要从网络上的任何其他位置加载文件,则getResource无法正常工作。

InputStream is =XYZ.class.getClassLoader().getResourceAsStream("/config.properties");
Properties prop = new Properties();
prop.load(is);

In this case, I'm getting nullPointerException. 在这种情况下,我会得到nullPointerException。 Let me know if you need more details. 让我知道您是否需要更多详细信息。

jar content Heirarchy jar内容层次结构

Properties file - /java-file-io-application/src/main/resources/config.properties
XYZ class - /java-file-io-application/src/main/java/org/bc/xyz/iplugin/utilities/XYZ.java

Looks like you might be building your jar incorrectly. 看起来您可能不正确地构建了jar。 Files from 'src/main/resources' would be expected at the root of the jar file. 来自“ src / main / resources”的文件应该在jar文件的根目录下。 If your jar file contains the 'src/main/resources' directory, something's off with your build. 如果您的jar文件包含“ src / main / resources”目录,则说明您的构建存在问题。

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

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