简体   繁体   中英

How to load property file located inside jar file

How to load property files placed in resource folder of an executable jar file. Here my app itself is a jar and it executes on it own. 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. It throws NullPointerException. Only problem I see here is that jar is not able to pick the property files with given path. Any help would be appreciated.

Method 1: Using Apache Commons Configuration

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

In above case I'm getting ConfigurationException. Class is not able to find file mentioned in given path.

Method 2: Using getResourceAsStream. I know that getResource doesn't work if we are to load files from network on in any other location.

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

In this case, I'm getting nullPointerException. Let me know if you need more details.

jar content Heirarchy

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. Files from 'src/main/resources' would be expected at the root of the jar file. If your jar file contains the 'src/main/resources' directory, something's off with your build.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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