HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java Read and Write Properties File Example

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

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. vittal

    January 31, 2020

    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();
            }
        }
    }
  2. vittal

    January 31, 2020

    We have to save the property file after setting the property, otherwise the actual property file still has old values.

  3. ranganath

    April 14, 2018

    Hi

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

  4. a@gmail.com

    January 23, 2018

    where should we place the prorperty file

  5. Soleil

    October 10, 2017

    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!

  6. Alexander Shakhov

    October 9, 2016

    I have ExceptionInInitializerError

  7. Aman

    April 4, 2015

    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

    • Lokesh Gupta

      April 5, 2015

      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.

  8. Java Learner

    March 11, 2015

    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

    • Lokesh Gupta

      March 15, 2015

      Yes, store the escaped URL e.g. url=http://www.example.org/test. Read URL and redirect using framework you are using.

  9. Arvind singh

    March 9, 2015

    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 ?

  10. Ram

    February 6, 2015

    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?

    • Shiva

      March 3, 2016

      There is an IOException catch block

  11. vaibhav

    November 24, 2014

    Hi sir can u tell me how to use property file while reading a BLOB file from mysql database using jdbc?and save it.thanks.

  12. hemanth212hemanth

    August 11, 2014

    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?

    • Lokesh Gupta

      August 11, 2014

      Absolutely, I do not see any harm in doing so.

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)