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


Page:    1 2 >

The JavaSW Properties class offers a very convenient method of storing data for your application. It consists of various String values and String keys that you use to look up these values. It is basically a hashtable. The load method of the Properties class offers a very convenient mechanism for loading key/value String pairs from a properties file in the file system.

Let's create a ReadPropertiesFile class. This class reads in properties from a 'test.properties' file at the root level of our project.

'testing' project

The ReadPropertiesFile class creates an input stream from the test.properties file. It creates a Properties object and loads the properties (key/value pairs) from the input stream. It then enumerates over the keys of the Properties object, and retrieves the value for each key. The key/value pairs are displayed via standard output.

ReadPropertiesFile.java

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

public class ReadPropertiesFile {
	public static void main(String[] args) {
		try {
			File file = new File("test.properties");
			FileInputStream fileInput = new FileInputStream(file);
			Properties properties = new Properties();
			properties.load(fileInput);
			fileInput.close();

			Enumeration enuKeys = properties.keys();
			while (enuKeys.hasMoreElements()) {
				String key = (String) enuKeys.nextElement();
				String value = properties.getProperty(key);
				System.out.println(key + ": " + value);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

The contents of the test.properties file are displayed below. Each key is represented on the left side of the = sign, and each value is on the right side of the = sign. Comments are designated by lines starting with # signs.

test.properties

# This is my test.properties file
favoriteFood=kun pao chicken
favoriteVegetable=artichoke
favoriteSoda=Dr Pepper

(Continued on page 2)

Page:    1 2 >