Java Properties file examples

Normally, Java properties file is used to store project configuration data or settings. In this tutorial, we will show you how to read and write to/from a .properties file.


	Properties prop = new Properties();
	
	// set key and value
	prop.setProperty("db.url", "localhost");
	prop.setProperty("db.user", "mkyong");
	prop.setProperty("db.password", "password");
		
	// save a properties file
	prop.store(outputStream, "");

	// load a properties file
	prop.load(inputStream)
	
	// get value by key
	prop.getProperty("db.url");
    prop.getProperty("db.user");
    prop.getProperty("db.password");
			
	// get all keys
	prop.keySet();
	
	// print everything
	prop.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v));

A simple Maven project structure for testing.

project directory

1. Write to the properties file

Set the property key and value, and save it somewhere.

App1.java

package com.mkyong;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class App1 {

    public static void main(String[] args) {

        try (OutputStream output = new FileOutputStream("path/to/config.properties")) {

            Properties prop = new Properties();

            // set the properties value
            prop.setProperty("db.url", "localhost");
            prop.setProperty("db.user", "mkyong");
            prop.setProperty("db.password", "password");

            // save properties to project root folder
            prop.store(output, null);

            System.out.println(prop);

        } catch (IOException io) {
            io.printStackTrace();
        }

    }
}

Output


{db.user=mkyong, db.password=password, db.url=localhost}

The path/to/config.properties is created.

path/to/config.properties

#Thu Apr 11 17:37:58 SRET 2019
db.user=mkyong
db.password=password
db.url=localhost

2. Load a properties file

Load a properties file from the file system and retrieved the property value.

App2.java

package com.mkyong;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class App2 {

    public static void main(String[] args) {

        try (InputStream input = new FileInputStream("path/to/config.properties")) {

            Properties prop = new Properties();

            // load a properties file
            prop.load(input);

            // get the property value and print it out
            System.out.println(prop.getProperty("db.url"));
            System.out.println(prop.getProperty("db.user"));
            System.out.println(prop.getProperty("db.password"));

        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

Output


localhost
mkyong
password

3. Load a properties file from classpath

Load a properties file config.properties from project classpath, and retrieved the property value.

src/main/resources/config.properties

db.url=localhost
db.user=mkyong
db.password=password
App3.java

package com.mkyong;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class App3 {

    public static void main(String[] args) {

        try (InputStream input = App3.class.getClassLoader().getResourceAsStream("config.properties")) {

            Properties prop = new Properties();

            if (input == null) {
                System.out.println("Sorry, unable to find config.properties");
                return;
            }

            //load a properties file from class path, inside static method
            prop.load(input);

            //get the property value and print it out
            System.out.println(prop.getProperty("db.url"));
            System.out.println(prop.getProperty("db.user"));
            System.out.println(prop.getProperty("db.password"));

        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

Output


localhost
mkyong
password

4. Prints everything from a properties file

Load a properties file config.properties from project classpath, and print out the keys and values.

App4.java

package com.mkyong;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

public class App4 {

    public static void main(String[] args) {
        App4 app = new App4();
        app.printAll("config.properties");
    }

    private void printAll(String filename) {

        try (InputStream input = getClass().getClassLoader().getResourceAsStream(filename)) {

            Properties prop = new Properties();

            if (input == null) {
                System.out.println("Sorry, unable to find " + filename);
                return;
            }

            prop.load(input);

            // Java 8 , print key and values
            prop.forEach((key, value) -> System.out.println("Key : " + key + ", Value : " + value));

            // Get all keys
            prop.keySet().forEach(x -> System.out.println(x));

            Set<Object> objects = prop.keySet();

            /*Enumeration e = prop.propertyNames();
            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                String value = prop.getProperty(key);
                System.out.println("Key : " + key + ", Value : " + value);
            }*/

        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

Output


Key : db.user, Value : mkyong
Key : db.password, Value : password
Key : db.url, Value : localhost
db.user
db.password
db.url

Download Source Code

Download – java-properties-file.zip (6KB)

References

137 comments on “Java Properties file examples

  1. Can we read from class path and store in the same class path with different file name.
    I need to update the application.properties with the application-prod.properties

  2. Can .load be used to read a property file of another Java app within the same package? Like I want to read the other java apps .property file, create an Enum Map of key value pair and then compare it to the property file in the calling Java app. Thanks

  3. I included this as a jar in my main application. Not getting any errors but I am unable to see .properties file being created on liberty server and subsequently properties not getting loaded in other java files.

  4. Hello, i’m new to java, can u tell me what’s the different between point 2 (Load a properties file from the file system) and point 3 (Load a properties file config.properties from project classpath), and can you suggest me when i should use point 2 or point 3 ? Thank you very much.

    1. Article is updated, for App1 and App2, you need to defined your own location, by default it will saved into the project root folder.

      For App3, it loads from src/main/resources/config.properties

  5. how to add html tags and affect in front-end through resource bundle file, Ex: i need to show bolder text front-end, i tried BOLDER but it doesn’t work.

  6. Hi Kyong, Can you please explain how to use properties file in Java web application. And how to pass when running the same from server(Glassfish)

  7. In your third example, you write:

    input = App3.class.getClassLoader().getResourceAsStream(filename);

    This should probably be App.class ….

    Also, I believe that for AutoCloseable streams the following approach is a good practice:

    final String PROPS = “main.properties”;
    final Properties properties = new Properties();
    try (final FileInputStream in = new FileInputStream(PROPS)) {
    if (null != in) {
    properties.load(in);
    } else {
    throw new IOException(String.format(“file %s not found in classpath”, PROPS));
    } catch (IOException e) {
    System.out.printf(“Loading of properties was not performed, reason: %s%n”, e.getMessage());
    }

    Or for resources:

    final String PROPS = “main.properties”;
    final Properties properties = new Properties();
    try (final InputStream in = getClass().getClassLoader().getResourceAsStream(PROPS)) {
    if (null != in) {
    properties.load(in);
    } else {
    throw new IOException(String.format(“file %s not found in classpath”, PROPS));
    }
    } catch (IOException e) {
    System.out.printf(“Loading of properties was not performed, reason: %s%n”, e.getMessage());
    }

  8. static public void main(String args[]) throws IOException {

    Properties prop = new Properties();

    InputStream input = new FileInputStream(“F:\workspace\Practice\config.properties”);

    prop.load(input);

    Set set = prop.keySet();

    for (Object r : set) {
    System.out.println(r + ” value is: ” + prop.getProperty((String) r));

    }

    }

  9. i followed the tutorial, using this code:
    1. Write to properties file
    tested the code on a tomcat but not create the file why? how to know why?
    2) in wich path was created the file?
    my tomcat is installed on /opt/tomcat

    not i tested sam ecode on a glassfish server and worked, created the file on:
    /opt/glassfish4/glassfish/domains/swManzana/config/

    and i am happy but in tomcat why not work?

    thanks

  10. how do i preserve the existing comments in the properties file, while still modifying a key value pair or two ?

  11. it is possible to use variables into a properties file? something like this:

    key=value1
    key2=value3
    key3=${value2}${value3}

  12. Hi,

    I’m always getting “Sorry, unable to find ” + filename in scenario 4

    Note: I have a properties file which works just fine with scenario no. 2

    Can you please help?

  13. Thanks for the post. I have a maven project with JPA, and I want the persistence.xml file is set with a data connection, you are in a properties file. Thanks for your help.

  14. Hi, thanks for the examples.

    You can still improve the “input.close()” part with the JAVA 7 “try-with-ressource” statement :
    example :

    try (InputStream input = new FileInputStream(PROPERTIES_FILE_NAME)) {

    properties.load(input);

    // (…. do some stuff …)

    } catch (IOException e) {

    e.printStackTrace();
    } finally {
    // don’t have to care about input.close() anymore here
    }

    Explained here http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

  15. Maybe you should set the properties as the System one’s, i.e.:

    prop.load(input);
    System.setProperties(prop);

    ?

  16. Thanks for the post. I have an issue. i am encrypting the password and storing in properties file. my input is admin123, after encryption it is “9GkMVi65yhKkf5PoVaFEWw==”, But after write to properties file it is showing like “9GkMVi65yhKkf5PoVaFEWw==”. Could you please suggest me to solve this. Thanks

  17. Hi mkyong,

    In my Java application I have been using similar code and I have issues with memory leak. To be precise, I have a helper class which has all static methods and in one of the static method, I load properties file but instead of readying key values in this method, I return “Properties” object to calling method. Calling method then reads key/values and does nothing to this returned properties (I mean no memory cleanup). Also in static method where I load properties file, I am not closing the “InputStreamReader”. My questions are:

    1) Will this lead to memory leak?
    2) If I close the “InputStreamReader” immediately after loading properties file, will the caller have access to all key/values? Is it a good practice to close stream reader immediately after it is used?

  18. The load method doesn’t close the input stream you give it. The input stream must be closed after the properties are loaded. Many people might follow the example and leave that leak in their code.

  19. I have a .properties file. I have to create a jsp page such that it reads the data from this .properties file and display it in table format.

    My .properties file s something like ERORECORDS = 600 DELAZERORECOS = 30 ANSYTIM = 900 DEDDEMADF = DEDREGF_ACUV DEDDEMAE = DEDREFG_REOG DESDPWDS = DEDCHGG_PWDP

    and goes on… I have to create a jsp page to show these data in a table format

    please help me

    1. Look at mkyongs tutorials on Spring MVC. You’ll be able to pass the values from the properties file into the JSP view from the controller.

  20. getting NullPointer exception in the 3rd scenario:-

    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.properties.reader.AppReaderCpath.main(AppReaderCpath.java:15)

  21. Hi,
    Thanks for the tutorial, it works for me when create servlet and deployed in tomcat. But I got NullPointerException in weblogic, The path for the properties file is in WEB-INF folder. Maybe you know why it failed?

    regards,
    Ruly

  22. This was so lucid and concise.
    You just saved half hour of my life by writing this article.

    May the force be with you!

    Best!
    Vijai

  23. I am writing testscripts and i saved all my datas in data.properties file. i added lot of comments and left some spaces between each datas. To run my scripts i need to update the property file and i tried the option
    for example ::
    prop.setProperty(“dbpassword”, “password”);
    prop.store(new FileOutputStream(“config.properties”), null);
    But after saving it deletes all the commented text and it rearrange the datas in it.

  24. Thank you so mutch, I just love this website, and you are not a computer that is printing(docs.oracle writes like a computer). Thank you again 🙂

    Im from sweden so my spelling isn’t that good

  25. I am typically to blogging and i actually respect your content. The article has actually peaks my interest. I’m going to bookmark your web site and hold checking for brand new information.

    1. I completely agree.
      EVERY SINGLE article I have read so far has been extremely helpful and straight to the point.

      Thanks. Keep it up

  26. Hi All,
    Can anyone please help me in finding out what all system properties are available during recovery time ?
    The System properties for eg: ro.product.xxx that are available,when the device is fully booted up , is different from when the device is in recovery mode.

    The requirement is to access few system properties during recovery mode.
    Thanks in Advance !

      1. Device = Android Tablet
        Recovery Time = I didn’t get this. This recovery mode is same as when
        we see the recovery screen for OTA updates.

  27. Hi MK,thanks for your post,but my requirement is little different.I want edit an existing property file at runtime.Suppose there is key value like name=sanjib but at runtime i want to change it to name=sanjibdhar.Is it possible and how??

  28. Just wanted to say that THIS IS AWESOME. I’ve been looking for straight-up source code on how to do this for a while. Perfect. THANKS!

  29. Hello,
    I am trying to make the property file, but while i am adding any special character in the value of the key value pair, it appends a ‘/’ in front of that.

    like

    prop.setProperty(“database.url”, “jdbc:oracle:thin:@localhost:1521:xe”);

    but in the property file, it is stored as

    database.url=jdbc\:oracle\:thin\:@localhost\:1521\:xe

    Please help, its quite urgent.
    Thanks in advance

    1. The \ character is added to escape the specials chars like :. If you test your code with a simple

      System.out.println(prop.get("database.url"));
      

      you will see that your property is as expected, without \ char.

      1. Thnx for the reply, but I want to write that in the property file as it is(*its kind of requirement), and the ordering is also not right. Its getting saved randomly.

        I want it to be in the manner, I am writing it.

        So, any help on this..???

  30. When I write my Properties to a file, there is always a ‘\’ at the 40th character of each key-value pair. But the properties file work perfectly after reading back. Why?

  31. I use Properties.store() method to store my properties. But it was add a ‘\’ at the 40th characters of each line, i.e. My…..Properties.lastDate2=30/07/2012 13\:35

    I read back the file with Properties.load() and it works perfectly. Is there a way to get rid of the ‘\’?

  32. Thank you so much…you saved me from lots of unnecessary hard work..had searched for solution at so many places but your posting helped me greatly …thanks

  33. could you explane what this part of code in .properties file will do?
    logPropFileName = D:\\Program Files\\Corillian\\DMS-PA\\conf\\PA-log4j_cnet.properties
    paHistoryFile=D:\\FTP_Dir\\Current\\PaymentHistoryCNet.xml
    paReturnFile=D:\\FTP_Dir\\Current\\ReturnCNet.xml
    paRejectFile=D:\\FTP_Dir\\Current\\RejectCNet.xml
    paCheckFile=D:\\FTP_Dir\\Current\\CheckCNet.xml

  34. I am goning through the some BAT files and i am not getting this part
    com.corin.pa.facade.CheckUpdateFacade d:/”program files”/Corin/DM-PA/scripts/system_b.properties
    what does this part is doing actually?

  35. Hi,
    to my understanding of file operation, when loading properities from a file, the FileInputStream shall be closed.

            FileInputStream fin;
        	try {
                  //load a properties file
                  fin = new FileInputStream("config.properties");
        	      prop.load(fin);
     
                  //get the property value and print it out
                  System.out.println(prop.getProperty("database"));
        	      System.out.println(prop.getProperty("dbuser"));
        	      System.out.println(prop.getProperty("dbpassword"));
     
        	} catch (IOException ex) {
        	      ex.printStackTrace();
            } finally {
                  fin.close();
            }
    
    1. There should be added 2 more things, fin should be initialized and the close operation should be on try catch:
      pre lang=”java”>

      FileInputStream fin = null;
      try {
      // load a properties file
      fin = new FileInputStream(“config.properties”);
      prop.load(fin);

      // get the property value and print it out
      System.out.println(prop.getProperty(“database”));
      System.out.println(prop.getProperty(“dbuser”));
      System.out.println(prop.getProperty(“dbpassword”));

      } catch (IOException ex) {
      ex.printStackTrace();
      } finally {
      try {
      fin.close();
      } catch (IOException e) {
      }
      }

  36. hello

    I need to get only the three first lines of a .properties file in Java.

    The problem I am facing is that I’m getting all the lines of the file with that method:

     
    
    public void displayProperties(Properties props) {
    
        Iterator it = props.keySet().iterator();
    
        while (it.hasNext()) {          
    
            //propertyName = (String) it.next();
            propertyName = (String) it.next();
            propertyValue = props.getProperty(propertyName);
    }
    

    I need to fill in an array with the three first properties I get, so how can I read only the three first lines?

  37. i am sorry my prev message i could nt see properly that is why i’m giving again

    i added the class path as whole path, and also from project

    value=”classpath:/home/dev06/filesys/config/info.properties”

    and

    value = “classpath: filesys/config/info.properties”

    i am getting FileIOnotfoundException and it cound nt read or load

    1. I have the same problem in a netbeans project. I’m trying to read the config file from another folder (actually a package) in the project, so I’ve got:

      main project folder (package)
      |
      +- main class
      |
      +- sub-folder (package)
      | |
      | +- java file from which the call to load the properties file is made
      |
      +- sub-folder (package) for the properties
      |
      +- properties file

      I’ve tried every type of relative path I can think of:

      * config.properties
      * properties/config.properties
      * ../properties/config.properties
      * ../../properties/config.properties

      … and some more, but nothing seems to work. I still get a file not found exception.

      Any suggestions gratefully received.

      Cheers

      Peter

      1. Below code works if your .properties file is present in src/main/resources folder

          <property name="location"
        value="classpath:Information.properties" />
        </bean>
        

        and this code does the trick to keep ur .properties file out side src and u can customize at any point of time

        <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location"
        value="file:${config.files.dir}/information.properties" />
        </bean>
        

        in this way

         
        <bean id="placeholderConfig"
        		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        		<property name="location"
        			value="file:/home/dev06/Properties/Information.properties" />
        	</bean>
        
        
        1. Thanks. I guess that works if you’re using a framework, but I’m not. It’s just a plain vanilla (NetBeans) Java project.

          (I couldn’t find a framework for Java that wasn’t either Web or Java EE centric).

          Cheers

          Peter

  38. Hello, how to read .properties file, present in outside the src folder

    for example i have a .properties file. i dont want to keep this in src folder, so i created a new folder config, and i added my .properties file

    i gave code as class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>

    and also class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>

    but still i am gettingthis message

    Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [resource/Information.properties] cannot be opened because it does not exist

    any help will be appreciated

  39. Quick question, what if I would like to write to the file multiple times. I tried this solution, but it creates a new file and I loose previous written sections.
    Thanks,
    Homer

  40. Always find your hints/notes (no matter how small) very helpful!!!

    Any advice on loading properties several directories up? Unfortunately relative and “../” format for going back a directory doesnt seem to work.

    1. Hi i nee small information reg to properties file in struts1.3

      i want to add some extra msg to properties file is it possible?????if s kindly reply me ASAP

      i want to print action message like “20 records inserted successfully” here 20 is dynamic i don’t know the exaact value……

Leave a Comment

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