Java Read and Write Properties File Example

In this Java tutorial, learn to read properties file using Properties.load() method. Also we will use Properties.setProperty() method to write a new property into the .properties file.

1. Setup

Given below is a property file that we will use in our example.

firstName=Lokesh
lastName=Gupta
blog=howtodoinjava
technology=java

2. Reading Properties File

In most applications, the properties file is loaded during the application startup and is cached for future references. Whenever we need to get a property value by its key, we will refer to the properties cache and get the value from it.

The properties cache is usually a singleton static instance so that application does not require to read the property file multiple times; because the IO cost of reading the file again is very high for any time-critical application.

Example 1: Reading a .properties file in Java

In the given example, we are reading the properties from a file app.properties which is in the classpath. The class PropertiesCache acts as a cache for loaded properties.

The file loads the properties lazily, but only once.

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

public class PropertiesCache
{
   private final Properties configProp = new Properties();
   
   private PropertiesCache()
   {
      //Private constructor to restrict new instances
      InputStream in = this.getClass().getClassLoader().getResourceAsStream("application.properties");
      System.out.println("Reading all properties from the file");
      try {
          configProp.load(in);
      } catch (IOException e) {
          e.printStackTrace();
      }
   }

   //Bill Pugh Solution for singleton pattern
   private static class LazyHolder
   {
      private static final PropertiesCache INSTANCE = new PropertiesCache();
   }

   public static PropertiesCache getInstance()
   {
      return LazyHolder.INSTANCE;
   }
   
   public String getProperty(String key){
      return configProp.getProperty(key);
   }
   
   public Set<String> getAllPropertyNames(){
      return configProp.stringPropertyNames();
   }
   
   public boolean containsKey(String key){
      return configProp.containsKey(key);
   }
}

In the above code, we have used Bill Pugh technique for creating a singleton instance.

Let’s test the above code.

public static void main(String[] args)
{
  //Get individual properties
  System.out.println(PropertiesCache.getInstance().getProperty("firstName"));
  System.out.println(PropertiesCache.getInstance().getProperty("lastName"));
  
  //All property names
  System.out.println(PropertiesCache.getInstance().getAllPropertyNames());
}

Program Output:

Read all properties from file
Lokesh
Gupta
[lastName, technology, firstName, blog]

3. Writing into the Property File

Personally, I do not find any good reason for modifying a property file from the application code. Only time, it may make sense if you are preparing data for exporting to third party vendor/ or application that needs data in this format only.

Example 2: Java program to write a new key-value pair in properties file

So, if you are facing similar situation then create two more methods in PropertiesCache.java like this:

public void setProperty(String key, String value){
  configProp.setProperty(key, value);
}

public void flush() throws FileNotFoundException, IOException {
	try (final OutputStream outputstream 
				= new FileOutputStream("application.properties");) {
		configProp.store(outputstream,"File Updated");
		outputstream.close();
	}
}
  • Use the setProperty(k, v) method to write new property to the properties file.
  • Use the flush() method to write the updated properties back into the application.properties file.
PropertiesCache cache = PropertiesCache.getInstance();
if(cache.containsKey("country") == false){
 cache.setProperty("country", "INDIA");
}

//Verify property
System.out.println(cache.getProperty("country")); 

//Write to the file
PropertiesCache.getInstance().flush(); 

Program Output:

Reading all properties from the file
INDIA 

And the updated properties file is:

#File Updated
#Fri Aug 14 16:14:33 IST 2020
firstName=Lokesh
lastName=Gupta
technology=java
blog=howtodoinjava
country=INDIA

That’s all for this simple and easy tutorial related to reading and writing property files using java.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

16 thoughts on “Java Read and Write Properties File Example”

  1. Please find the code snippets for normal property file updation

    public class ReadingProp {
        public static void main(String args[]) {
            ReadingProp readingProp = new ReadingProp();
            readingProp.ReadProperties();
        }
    
        public void ReadProperties() {
            Properties properties = new Properties();
            try (final InputStream inputStream = this.getClass().getResourceAsStream("xyz.properties")) {
                properties.load(inputStream);
                System.out.println(properties.getProperty("rama"));
                properties.setProperty("rama", "lakshmana");
                String path= this.getClass().getResource("jaanu.properties").getPath();
                OutputStream output = new FileOutputStream(path);
                properties.store(output,"comments are there");
                output.close();
                inputStream.close();
                System.out.println(properties.getProperty("rama"));
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    Reply
  2. Hi

    Iam working on rest ssured. i am stuck at how to write/replace attribute in property file. i am looking for solution/suggestion

    Reply
  3. Hi friend, thanks for your helpful topic but for the 2nd section “write to Property File Example”, I tested but it not write new or update value to properties file? Please take a look about it!

    Reply
  4. Hi Lokesh,

    Firstly, I would like to thank you for writing articles on java which are easy to understand with great examples.

    Secondly, I have a question, what if I have to process multiple properties files in my project.
    One vague option I can think of is creating separate class per properties file. Which doesn’t sound good to me

    Thirdly, if I need to update a value or introduce a new pair in my properties file then I will have to restart my application, which I see as a small draw back in making a singleton instance. What do you think?

    Thanks,
    A

    Reply
    • Hi Aman, Managing one property file from one class OR multiple properties files from one class is a matter of situation in hand. The decision shoul be made logically. If it’s logical to group some of properties file, then manage them from one class file, if not logical then create separate files. I usually do not prefer more than 3-4 properties file in a application (for configuration purposes; excluding i18n). And chances are that you will need to read/write only a certain file in very specific scenarios; rest are usually directly feed to frameworks e.g. spring or struts.

      Regarding singleton, they are supposed to be immutable as best practice. But it’s not mandatory. No need to restart the application.

      Reply
  5. Hi,
    I want to add a hyperlink in the value (of key , value pair )in properties file, which should redirect me to my desired page of website. How can i do that

    Reply
  6. It’s crystal clear concept, but can you tell me how to apply that concept in configure hibernate.cfg.xml file . I don’t know how to configure the hibernate properties vai using properties file ?

    Reply
  7. Hi, Lokesh, your solution for properties loading is very clean and nice. The only question I have is, you are not handling the IOException that may be thrown during loading the properties. How can we handle, can you please share?

    Reply
  8. Really best way to read properties file .. but one clarification needed is is .. where should i Keep properties file..Is it good enough if its Class Path?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.