Loading Java Properties Files

Java Properties files are amazing resources to add information in Java. Generally these files are used to store static information in key and value pair. Things that you do not want to hard code in your Java code goes into properties files. Although there are multiple ways of loading properties file, I will be focusing on loading the resource bundle files from class path resources. There are advantages of adding properties files in the classpath:
  1. The properties files became a part of the deployable code (e.g. JAR file) making it easy to manage.
  2. Properties files can be loaded independent of the path of source code.
Let us see the simple way of Loading a property file in Java code. There are two ways of loading properties files in Java. 1. Using ClassLoader.getResourceAsStream() 2. Using Class.getResourceAsStream() In our example we will use both methods to load a properties file. Following is the content of sample properties file. The properties file will be in package net.viralpatel.resources. net/viralpatel/resources/config.properties
hello.world=Hello World
Code language: Java (java)
To load properties file using Classloader, use following code:
this.getClass() .getResourceAsStream("/some/package/config.properties");
Code language: Java (java)
The Class.getResourceAsStream(name) returns an Inputstream for a resource with a given name or null if no resource with the given name is found. The name of a resource is a ‘/’-seperated path name that identifies the resource. If the name with a leading “/” indicates the absolute name of the resource is the portion of the name following the ‘/’. In Class.getResourceAsStream(name), the rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object’s class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String). So in our example to load config.properties we will have a method loadProps1().
private Properties configProp = new Properties(); ... public void loadProps1() { InputStream in = this.getClass().getResourceAsStream("/net/viralpatel/resources/config.properties"); try { configProp.load(in); } catch (IOException e) { e.printStackTrace(); } }
Code language: Java (java)
To load properties file using Classloader, use following code:
this.getClass() .getClassLoader() .getResourceAsStream("some/package/config.properties");
Code language: Java (java)
The ClassLoader.getResourceAsStream(name) returns an Inputstream for reading the specified resource or null if the resource could not be found. The name of a resource is a ‘/’-seperated path name that identifies the resource. The name no leading ‘/’ (all namea are absolute). So in our example to load config.properties we will have a method loadProps2().
private Properties configProp = new Properties(); public void loadProps2() { InputStream in = this.getClass().getClassLoader().getResourceAsStream("net/viralpatel/resources/config.properties"); try { configProp.load(in); } catch (IOException e) { e.printStackTrace(); } }
Code language: Java (java)
The folder structure of our example code will be: java-load-properties The full Java code for testing
package net.viralpatel.java; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.ResourceBundle; public class LoadPropertiesExample { private Properties configProp = new Properties(); public static void main(String[] args) { LoadPropertiesExample sample = new LoadPropertiesExample(); sample.loadProps2(); sample.sayHello(); } public void loadProps1() { InputStream in = this.getClass().getResourceAsStream("/net/viralpatel/resources/config.properties"); try { configProp.load(in); } catch (IOException e) { e.printStackTrace(); } } public void loadProps2() { InputStream in = this.getClass().getClassLoader().getResourceAsStream("net/viralpatel/resources/config.properties"); try { configProp.load(in); } catch (IOException e) { e.printStackTrace(); } } public void sayHello() { System.out.println(configProp.getProperty("hello.world")); } }
Code language: Java (java)

Further Reading

Java ClassLoader API Java World – Smartly Loading Properties Files
Get our Articles via Email. Enter your email address.

You may also like...

33 Comments

  1. rakesh juyal says:

    Such a long article for so simple thing.

  2. JavaMan says:

    Interesante aqui te dejo mis dos Blogs. Aqui encontraras cosas tambien muy interesantes:

    http://viviendoconjavaynomoririntentandolo.blogspot.com

    http://frameworksjava2008.blogspot.com

    Saludos.

  3. ppow says:

    Asking the class itself for resources seems weird to me. Is there any way to get that by asking the System or by other API not connected to the class you are using it in?

  4. r4ds says:

    Hi..
    To load the property file in Java I think, it is very easy to do it. It will come in the form of directory when you are downloading this files..
    In Java 6 updated version, every properties class have been existed, take help form there to fulfil the requirements….

  5. muski says:

    Simple method to load properties file.

    Properties props = new Properties();
    props.load(new FileInputStream(“config.properties”));
    String value = props.getProperty(“prop1”);
    System.out.println(value);
    System.out.println(props.entrySet());

    • sneha says:

      Thank you Muski .. useful one :)

  6. test says:

    Thanks man,
    awesome post.
    helped me in reading the properties file outside the jar file.

    Thanks again

  7. Fishinastorm says:

    Hi Viral,
    NIce post. HOw do store some modified properties to the file in the same package as you mentioned. I used FileOutputstream, but it creates a new properties file elsewhere..i want the same properties file to contain the modified values…i am goign berserk with this…

  8. Thanks Dude
    Very good Post.
    I was struggling like anything.
    My problem was to load dataset file from resource folder (in DBUnit)
    return new FlatXmlDataSetBuilder().build(this.getClass().getResourceAsStream(“/dataset.xml”));

    thanks again;

  9. Misty says:

    Could you tell me how to include the properties file path in my manifest? my properties file is in the resources folder. I need to include this in the class path of the JAR file, so that if any user wants they can modify the properties file externally and it will reflect in the JAR file

  10. Curioso says:

    Very good, thanks

  11. Sathish Kumar says:

    This is very useful and very easy to understand. Thanks a lot… LOL

  12. dave51 says:

    Nice post. But I have to mantain a properties file out of MyProject.war file. In my environment I have a deploy directory to put the MyProject.war file, a log directory and a conf directory to put configuration.properties file. Using this good suggenstion configuration.properties file is embedded in MyProject.war file. Any Advice?

  13. Mekbib says:

    I have found it very helpful.
    Thanks for posting.

  14. Raja says:

    hi ,
    how to use the same properties file(net/viralpatel/resources/config.properties) into jsp page using jquery.

  15. lochan says:

    can we write multiple sql queries in properties file…? if yes then how to retrieve a single out of them.
    Please reply asap

  16. isa says:

    Hi,
    Nice tutorial.
    One potential issue that i observe here is that the name of the properties files has been hard coded in the code. you could get away by using -D option in the command line.
    Isa

  17. Michael Fernando says:

    Thanks. This cleared my confusion.

  18. Lucia says:

    Hello !
    I tried in Eclipse your code and gives:
    Exception in thread “main” java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Unknown Source)
    at java.util.Properties.load0(Unknown Source)
    at java.util.Properties.load(Unknown Source)
    at com.ion.ysura.garage.LoadPropertiesExample.loadProps2(LoadPropertiesExample.java:30)
    at com.ion.ysura.garage.LoadPropertiesExample.main(LoadPropertiesExample.java:14)

    Can you help?

  19. Lucia says:

    Sorry !
    I fixed it !!
    Do not start the path with /.
    Do as:
    prop.load(OpenGarage.class.getClassLoader().getResourceAsStream(“com/ion/ysura/garage/resources/config.properties”));

    Good examples !!

  20. Marco says:

    This approach doesn’t work if the properties file is outside the jar…

  21. Nice explanation dude , u made it like a piece of cake.
    I found an interesting explanation here also , this guy explained in a funny way or i shud say comic way dats what he had given the title.

  22. Kiko says:

    Thankx ! The snapshot of eclipse showed me something i was really missing!
    Great Article

  23. nishant says:

    Hi,

    Read from properties file with hard-code, everything works fine but when I introduce framework ,it gives null pointer exception why?

    //Hard code
    public class tt {
    public static void main(String[] args) throws IOException {
    Properties CONFIG= new Properties();
    FileInputStream ip = new FileInputStream(System.getProperty(“user.dir”)+”//src//com//app//config/config.properties”);
    CONFIG.load(ip);
    System.out.println(System.getProperty(“user.dir”));
    System.out.println(CONFIG.getProperty(“url_dbname”));
    }
    }

  24. nishant says:

    Try to read following code from properties file, generate null point exception.
    Please help and thanks in advance.

    public class Test_Login extends TestBase {
    public static void main(String[] args) throws SQLException {
    String dburl=”jdbc:mysql://localhost:”;
    String port=”3306″;
    String dbname=”/test”;
    String username=”root”;
    String password=” root”;
    Connection conn=null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;
    System.out.println(“establish connection db first test”);
    try {
    Class.forName(CONFIG.getProperty(“Db_driver”)).newInstance();
    } catch (InstantiationException | IllegalAccessException
    | ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    conn=DriverManager.getConnection(dburl+port+dbname, username,password);
    }
    }

  25. Nenad says:

    Could you please give your comment on this question on StackOverflow?
    http://stackoverflow.com/questions/23854130/eclipse-java-file-fileinputstream-vs-input-stream-when-loading-font-file

    You see, this (as you suggested) works:

    fis = this.getClass().getClassLoader().getResourceAsStream("examples/resources/verdana.ttf") 

    but this doesn’t (neither in Eclipse nor in runnable JAR)

    fis = this.getClass().getResourceAsStream("/examples/resources/vedrana.ttf"); 

    In if I understood you post correctly the other option should work as well?
    Where did I go wrong?

  26. srinath says:

    such a simple explanation is very easy to understand.Thanx a lot man.

  27. J Moore says:

    Thanks a lot! Your explanation was the first one I could find that actually spelled out how to get Class.getResource(foo) working in Eclipse. I haven’t read through all the comments, so I may be repeating things: this technique works for anything you want loaded into a Java application in a non path-dependent way. I am using it to load an ICC color table, for instance.

  28. hardik says:

    Can i achieve localization ?

  29. vinodjai says:

    Thanks for sharing a good example.

    Can you please share about “how to update property file inside a jar” ?
    Writing back is little difficult when file is inside the jar. I tried it using below code but can not achive it.

    URL ourl = this.getClass().getResource("/config.properties");
    			config = new PropertiesConfiguration(ourl);
    
    			config.setProperty("lastupatedtime", String.valueOf(time.getTimeInMillis()));
    			config.save();
    

    this work fine when file is outside the jar.

  30. Mateen says:

    Thanks for the blog

  31. Mark says:

    I tried your example and I keep getting a null returned in the stream. I’m using RAD 8.5 and WAS 8.5. My properties file is under my Resources java project which is at the same level as the calling method:
    * EmailPrefJava
    ->Java Source
    ->com.usb.emailpref.util
    ->GenericPropertyManager.java
    ->Public GenericPropertyManager
    InputStream inputstream = this.getClass().getResourceAsStream(“/local/projects/emailpreferences/properties/emailpref.properties”);

    * Resources
    ->Local
    ->projects.emailpreferences.properties
    ->emailpref.properties

    I’ve tried the following:
    1) removing the leading slash from the path,
    2) prefacing the path with “/Resources”,
    3) removing all the folder references and leaving just the properties file name,
    4) changing “projects/emailpreferences/properties” to “projects.emailpreferences.properties”
    5) replaced the relative path with a direct path “d:\\projects\emailpreferences\properties” (and the file does exist there).

    The reason I don’t use the direct path is we have to move the properties files into the app’s EAR and now need to reference it from there.

    I’d really appreciate your help. Your’s is the closest example I’ve found of what we need.

  32. ugyen says:

    This one isn’t working in my case.
    I have a properties file called ‘smsConfig.properties’ inside a folder called ‘config’ which is located out of outside the source folder.
    Could someone plez help me on this.

Leave a Reply

Your email address will not be published. Required fields are marked *