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 !!

Comments

Subscribe
Notify of
guest
16 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode