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 theapplication.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 !!
Please find the code snippets for normal property file updation
We have to save the property file after setting the property, otherwise the actual property file still has old values.
Hi
Iam working on rest ssured. i am stuck at how to write/replace attribute in property file. i am looking for solution/suggestion
where should we place the prorperty file
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!
I have ExceptionInInitializerError
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
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.
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
Yes, store the escaped URL e.g. url=http://www.example.org/test. Read URL and redirect using framework you are using.
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 ?
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?
There is an IOException catch block
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.
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?
Absolutely, I do not see any harm in doing so.