How do I write a properties file?
Author: Deron Eriksson
Description: This Java tutorial describes how to write properties to a file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1


The JavaSW Properties class is a great class for storing data for your application, since it consists of a hashtable data structure of String keys with a String value for each key. The store method of the Properties class allows you to easily store your Properties object to a file.

Let's create a WritePropertiesFile class. This class will write a series of key/value pairs to a 'test2.properties' file at the root level of our project.

'testing' project

The WritePropertiesFile class creates a Properties object and puts three key/value pairs within the Properties object. Next, it opens an output stream to the test2.properties file. Finally, it calls the store method of the Properties object and includes a comment line.

WritePropertiesFile.java

package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class WritePropertiesFile {
	public static void main(String[] args) {
		try {
			Properties properties = new Properties();
			properties.setProperty("favoriteAnimal", "marmot");
			properties.setProperty("favoriteContinent", "Antarctica");
			properties.setProperty("favoritePerson", "Nicole");

			File file = new File("test2.properties");
			FileOutputStream fileOut = new FileOutputStream(file);
			properties.store(fileOut, "Favorite Things");
			fileOut.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

When WritePropertiesFile is executed, it generates the test2.properties file. This file includes the "Favorite Things" comment at the top of the file along with a comment showing when the properties file was created. Below that, it lists the three key/value pairs that we put in our Properties object.

test2.properties

#Favorite Things
#Sat Feb 24 00:10:53 PST 2007
favoriteContinent=Antarctica
favoriteAnimal=marmot
favoritePerson=Nicole

As you can see, moving a Properties Java object and a properties file is a simple yet effective method of storing application data.