Properties file is always used to store the configuration data or settings. In this example you will learn how to read or write properties file and read and set property value in properties file.

Properties file example 1

In this example, set the property value and write it into a properties file named “config.properties”. The new saved properties file will stored at your project root folder.

package com.mkyong.common;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
 
public class App 
{
    public static void main( String[] args )
    {
    	Properties prop = new Properties();
 
    	try {
    		//set the properties value
    		prop.setProperty("database", "localhost");
    		prop.setProperty("dbuser", "mkyong");
    		prop.setProperty("dbpassword", "password");
 
    		//save properties to project root folder
    		prop.store(new FileOutputStream("config.properties"), null);
 
    	} catch (IOException ex) {
    		ex.printStackTrace();
        }
    }
}

Output

The content of the file “config.properties”

#Mon Jan 11 18:54:40 MYT 2010
dbpassword=password
database=localhost
dbuser=mkyong

Properties file example 2

In this example, load a properties file “config.properties” and retrieved the saved property value.

package com.mkyong.common;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
 
public class App 
{
    public static void main( String[] args )
    {
    	Properties prop = new Properties();
 
    	try {
               //load a properties file
    		prop.load(new FileInputStream("config.properties"));
 
               //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();
        }
 
    }
}

Output

localhost
mkyong
password

Reference

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Properties.html

Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~