How do I read a properties file with a Resource Bundle?
Author: Deron Eriksson
Description: This Java tutorial describes how to read a properties file using a Resource Bundle.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


Page:    1 2 >

A ResourceBundle offers a very easy way to access key/value pairs in a properties file in a JavaSW application. As a demonstration of this, I created the ResourceBundleTest class and a src/test/bundletest/mybundle.properties file in a project, as shown here:

'testing' project

The ResourceBundleTest class references the mybundle.properties file via the ResourceBundle.getBundle("test.bundletest.mybundle") method call. Notice that the package of the properties file is specified (using .'s instead of /'s) and that the properties file name is specified without the .properties extension.

After getting the resource bundle, the ResourceBundleTest class iterates over all of the keys in mybundle.properties and displays each of the keys and its value.

ResourceBundleTest.java

package test;

import java.util.Enumeration;
import java.util.ResourceBundle;


public class ResourceBundleTest {

	public static void main(String[] args) {

		ResourceBundle rb = ResourceBundle.getBundle("test.bundletest.mybundle");
		Enumeration <String> keys = rb.getKeys();
		while (keys.hasMoreElements()) {
			String key = keys.nextElement();
			String value = rb.getString(key);
			System.out.println(key + ": " + value);
		}
	}

}

Here is the mybundle.properties file used in this example.

mybundle.properties

# bundle.properties
this=that
animal=dog

(Continued on page 2)

Page:    1 2 >