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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
98 Comment threads
34 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
104 Comment authors
Vinothyogendra kevreArfanSubhashmkyong Recent comment authors
newest oldest most voted
guava
Guest
guava

I can’t find config.properties file. Can anyone help me ?

vnjhvhjc
Guest
vnjhvhjc

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

What is App3?

Weston
Guest
Weston

I see how to read from the classpath but what about writing to it?

Adrian Balea
Guest
Adrian Balea

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?

kiran
Guest
kiran

can anyone help me how to retrieve pdfs from path stored in database

Yussel Luna
Guest
Yussel Luna

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

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

Thirumalai
Guest
Thirumalai

sir i need simplry programme of properties file pls reply my emaid:gthiru59@yahoo.com

Nemo
Guest
Nemo

Thanks a lot

Rajendran
Guest
Rajendran

really so good .i think this type of sample will be very useful to all

bcmoney
Guest
bcmoney

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.

niazi
Guest
niazi

thanx for your examples

Homer
Guest
Homer

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

Mick Barry
Guest
Mick Barry

You should close the stream used to write the properties to once you’re done writing.

http://helpdesk.objects.com.au/java/how-to-store-values-in-a-properties-file

Pallavi
Guest
Pallavi

very helpful.Thanx

trackback
Saving GUI Settings

[…] Java Properties file examples MSN: Chewbaka@RSBuddy.com Bots I Support: ChewbakaChinner, ChewbakaCooker   […]

trackback
Java – Write .properties | Eureka!

[…] Mkyong.com – Java Properties file examples TwitterLinkedInFacebookMoreDiggEmailRedditPrintStumbleUponLike this:LikeBe the first to like this […]

trackback
Java – Read .properties | Eureka!

[…] Mkyong.com – Java Properties file examples TwitterLinkedInFacebookMoreDiggEmailRedditPrintStumbleUponLike this:LikeBe the first to like this […]

Aitsh
Guest
Aitsh

This is Nice.
Simple and Straight 🙂

keny
Guest
keny

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

keny
Guest
keny

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

Ranjan
Guest
Ranjan

Hi All,

Please refer the below mentioned blog.. Solves the problem of FileIOnotfoundException

It;s simple technique to create a new package and include the property file within it..
So that makes the property file available within the JAR file.

http://viralpatel.net/blogs/2009/10/loading-java-properties-files.html

Thanks,
Ranjan

rourou
Guest
rourou

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?

Dave Myers
Guest
Dave Myers

This worked right out of the box. Perfect.

Bhushan Pinjarkar
Guest
Bhushan Pinjarkar

how should i update the .property file by a user interface html form..?

beginner
Guest
beginner

thank you

Yang Guang
Guest
Yang Guang

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

mani
Guest
mani

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?

mani
Guest
mani

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

Jomblick J
Guest
Jomblick J

Hi,
How to remove the timestamp added to the file, on writing?

Hirashree
Guest
Hirashree

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