Is it possible to read a properties file from a jar?

Posted on 2014-12-24
Medium Priority
Last Modified: 2014-12-28

I was just wondering if it was possible to read a properties file that was bundled with another jar file?

Appreciate any help or alternatives! (aside from including the properties file here... lol)
Question by:Errang Genevre
LVL 28

Assisted Solution

dpearson earned 1000 total points
ID: 40517320
Yes that should be possible.

It's been a while since I wrote any code like this (it always seems rather clumsy how you get resources and class loaders) but I think it's something like this sequence.  (There may be short cuts available to reduce the number of calls here - as I say it's been a while).

The basic idea is you get a class loader for the Jar file and then open a stream within the jar and read the properties file.

Along these lines (this code is just approximate - you'll likely need to tweak it):

	private static ClassLoader getClassLoader(File confFolder) throws Exception {
		ClassLoader loader = MyClass.class.getClassLoader();

		if (confFolder != null) {
			URL confURL = confFolder.toURI().toURL() ;
			URLClassLoader cls = new URLClassLoader(new URL[]{ confURL }, loader) ;
			loader = cls ;
		return loader ;

        // ConfFolder in your case should point to the jar file
        // propertiesFile would be the path within the jar
        public static Properties loadPropertiesFile(File confFolder, File propertiesFile) throws Exception {
		ClassLoader cls = getClassLoader(confFolder) ;
		InputStream input = cls.getResourceAsStream(propertiesFile); 
		Properties properties = new Properties() ;
		properties.load(input) ;
                return properties ;

Open in new window

Hope that helps,

LVL 86

Accepted Solution

CEHJ earned 1000 total points
ID: 40517471
InputStream in = getClass().getResourceAsStream("/p.properties");

Open in new window

is really all you need. The path is package-relative

Author Closing Comment

by:Errang Genevre
ID: 40520679

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
If you are a mobile app developer and especially develop hybrid mobile apps then these 4 mistakes you must avoid for hybrid app development to be the more genuine app developer.
Simple Linear Regression
Introduction to Processes

627 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question