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
97 Comment threads
34 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
103 Comment authors
yogendra kevreArfanSubhashDinesh CTugrul Karakaya Recent comment authors
newest oldest most voted
guava
Guest
guava

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

Luq
Guest
Luq

you can either give the exact directory or go one level higher i.e. src/main/resources/config.properties

Tugrul Karakaya
Guest
Tugrul Karakaya

You need to add to the project manually. ???

yogendra kevre
Guest
yogendra kevre

Ohhh man that you can create by your ownan that’s easy part

vnjhvhjc
Guest
vnjhvhjc

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

What is App3?

prudhvi
Guest
prudhvi

App3 is mistake there. It should be App.
That means the name of class thats all.

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

Nemo
Guest
Nemo

Thanks a lot

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

vasu
Guest
vasu

how to add html tags and affect in front-end through resource bundle file, Ex: i need to show bolder text front-end, i tried BOLDER but it doesn’t work.

DiNA
Guest
DiNA

My file is not getting picked up for reading. Please give me some suggestion

Vikas
Guest
Vikas

static public void main(String args[]) throws IOException {

Properties prop = new Properties();

InputStream input = new FileInputStream(“F:\workspace\Practice\config.properties”);

prop.load(input);

Set set = prop.keySet();

for (Object r : set) {
System.out.println(r + ” value is: ” + prop.getProperty((String) r));

}

}

Vikas
Guest
Vikas

a simple way to have key value pair printed

Miguel Enriquez
Guest
Miguel Enriquez

i followed the tutorial, using this code:
1. Write to properties file
tested the code on a tomcat but not create the file why? how to know why?
2) in wich path was created the file?
my tomcat is installed on /opt/tomcat

not i tested sam ecode on a glassfish server and worked, created the file on:
/opt/glassfish4/glassfish/domains/swManzana/config/

and i am happy but in tomcat why not work?

thanks

agreeya van
Guest
agreeya van

Good Article!!

JAHMK
Guest
JAHMK

Thanks!
worked fine.

Mohit Mahindroo
Guest
Mohit Mahindroo

how do i preserve the existing comments in the properties file, while still modifying a key value pair or two ?

Nico
Guest
Nico

Hi, is there a way to put properties in the GUI admin console from glassfish and get it via @Resource?

Manish Kumar
Guest
Manish Kumar

can we load property file values in netbeans reading property file from command line arguments

Nikhil
Guest
Nikhil

HI, Thanks for the tutorial, can u tell me how to set the Labels of a JSP page using Properties File, ???

VICTOR ANDRES CARVAJAL
Guest
VICTOR ANDRES CARVAJAL

Thanks for the post. I have a maven project with JPA, and I want the persistence.xml file is set with a data connection, you are in a properties file. Thanks for your help.

Jarda Pavlí?ek
Guest
Jarda Pavlí?ek

Great example. Better than find in own past code.

ptirup
Guest
ptirup

Hi, thanks for the examples. You can still improve the “input.close()” part with the JAVA 7 “try-with-ressource” statement : example : try (InputStream input = new FileInputStream(PROPERTIES_FILE_NAME)) { properties.load(input); // (…. do some stuff …) } catch (IOException e) { e.printStackTrace(); } finally { // don’t have to care about input.close() anymore here } Explained here http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Eyal
Guest
Eyal

Thanks! Great post!

Mark
Guest
Mark

Thanks :)

Pasqualino Imbemba
Guest
Pasqualino Imbemba

Maybe you should set the properties as the System one’s, i.e.:

prop.load(input);
System.setProperties(prop);

?

Kuldip Shah
Guest
Kuldip Shah

Hi mkyong, In my Java application I have been using similar code and I have issues with memory leak. To be precise, I have a helper class which has all static methods and in one of the static method, I load properties file but instead of readying key values in this method, I return “Properties” object to calling method. Calling method then reads key/values and does nothing to this returned properties (I mean no memory cleanup). Also in static method where I load properties file, I am not closing the “InputStreamReader”. My questions are: 1) Will this lead to memory… Read more »

Irfan Maulana
Guest
Irfan Maulana

how to sort based on alphabet key name, because when I create properties file is unsort by alphabet….
Anyone can tell me ???
Thank you

mkyong
Guest
mkyong

Thanks.

Ali
Guest
Ali

thanks nice job :)

Frederik Heick
Guest
Frederik Heick

If you want to preserve comments in your properties files. Have a look at the class/library I have made. (open source)

http://jhpropertiestyp.sourceforge.net/jhpropertiestyped/javadoc/dk/heick/properties/types/utils/CommentedProperties.html

http://jhpropertiestyp.sourceforge.net/

Neo
Guest
Neo

The load method doesn’t close the input stream you give it. The input stream must be closed after the properties are loaded. Many people might follow the example and leave that leak in their code.

mkyong
Guest
mkyong

Thanks, examples are updated with the ugly close steam statement.

Moreaki
Guest
Moreaki

Since you wrote this in 2014, I suggest to use the language features provided by at least JDK 1.7, which for the case of AutoCloseable objects suggests to use the try-with-resources approach (http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html). I’ve also left a comment regarding this further above.