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.

1. Write to properties file

Set the property value, and write it into a properties file named config.properties.

App.java

package com.mkyong.properties;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class App {
  public static void main(String[] args) {
	
	Properties prop = new Properties();
	OutputStream output = null;

	try {

		output = new FileOutputStream("config.properties");

		// set the properties value
		prop.setProperty("database", "localhost");
		prop.setProperty("dbuser", "mkyong");
		prop.setProperty("dbpassword", "password");

		// save properties to project root folder
		prop.store(output, null);

	} catch (IOException io) {
		io.printStackTrace();
	} finally {
		if (output != null) {
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
  }
}

Output

config.properties

#Fri Jan 17 22:37:45 MYT 2014
dbpassword=password
database=localhost
dbuser=mkyong

P.S If file path is not specified, then this properties file will be stored in your project root folder.

2. Load a properties file

Load a properties file from the file system and retrieved the property value.

App.java

package com.mkyong.properties;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class App {
  public static void main(String[] args) {

	Properties prop = new Properties();
	InputStream input = null;

	try {

		input = new FileInputStream("config.properties");

		// load a properties file
		prop.load(input);

		// 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 {
		if (input != null) {
			try {
				input.close();
			} catch (IOException e) {
				e.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.

P.S Assume properties file “config.properties” is in your project classpath root folder.

App.java

package com.mkyong.properties;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class App {

  public static void main( String[] args ){

    	Properties prop = new Properties();
    	InputStream input = null;
    	
    	try {
        
    		String filename = "config.properties";
    		input = App3.class.getClassLoader().getResourceAsStream(filename);
    		if(input==null){
    	            System.out.println("Sorry, unable to find " + filename);
    		    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("database"));
    	        System.out.println(prop.getProperty("dbuser"));
    	        System.out.println(prop.getProperty("dbpassword"));
 
    	} catch (IOException ex) {
    		ex.printStackTrace();
        } finally{
        	if(input!=null){
        		try {
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        	}
        }
 
    }
}

Output


localhost
mkyong
password

For non-static method, use this :


prop.load(getClass().getClassLoader().getResourceAsStream("config.properties"));

4. Prints everything from a properties file

Load a properties file config.properties from project classpath, and get the keys and values.

App.java

package com.mkyong.properties;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

public class App {

  public static void main(String[] args) {
	App app = new App();
	app.printThemAll();
  }

  private void printThemAll() {

	Properties prop = new Properties();
	InputStream input = null;

	try {

		String filename = "config.properties";
		input = getClass().getClassLoader().getResourceAsStream(filename);
		if (input == null) {
			System.out.println("Sorry, unable to find " + filename);
			return;
		}

		prop.load(input);

		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();
	} finally {
		if (input != null) {
			try {
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

  }

}

Output


Key : dbpassword, Value : password
Key : database, Value : localhost
Key : dbuser, Value : mkyong

References

  1. Java : GetResourceAsStream In Static Method
  2. Java Properties JavaDoc

About the Author

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

Comments

avatar
94 Comment threads
25 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
97 Comment authors
BennyMguavaprudhvivasuMartin 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?

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

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

Moreaki
Guest
Moreaki

In your third example, you write: input = App3.class.getClassLoader().getResourceAsStream(filename); This should probably be App.class …. Also, I believe that for AutoCloseable streams the following approach is a good practice: final String PROPS = “main.properties”; final Properties properties = new Properties(); try (final FileInputStream in = new FileInputStream(PROPS)) { if (null != in) { properties.load(in); } else { throw new IOException(String.format(“file %s not found in classpath”, PROPS)); } catch (IOException e) { System.out.printf(“Loading of properties was not performed, reason: %s%n”, e.getMessage()); } Or for resources: final String PROPS = “main.properties”; final Properties properties = new Properties(); try (final InputStream in =… Read more »

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

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}

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/