Using a ResourceBundle

Suppose we have a .properties file called LabelsBundle_nl_BE and assume also our default locale is en_US. To get access to that bundle, you can invoke ResourceBundle.getBundle(“LabelsBundle”, “nl”, “BE”). Notice that a resource bundle consists of two parts: a family name and a locale part. The locale part contains a language code, a country code and an optional variant code.

In our example, it will try to locate the bundle in the following way:

	class LabelsBundle_nl_BE		NOTFOUND
	file LabelsBundle_nl_BE.properties      OK
	class LabelsBundle_nl			NOTFOUND
	file LabelsBundle_nl.properties		NOTFOUND
	class LabelsBundle			NOTFOUND
	file LabelsBundle.properties		NOTFOUND

Notice that once the .propreties file has been located, it will still continue to look for parent resourcebundles by shortening the locale part delimited by an underscore.

Now assume we only have a .properties file called LabelsBundle_en and we invoke ResourceBundle.getBundle(“LabelsBundle”, “nl”, “BE”). Notice here that it will start from our desired locale and build its way up the tree, including searching for a match with the default locale.

	class LabelsBundle_nl_BE		NOTFOUND
	file LabelsBundle_nl_BE.properties	NOTFOUND
	class LabelsBundle_nl			NOTFOUND
	file LabelsBundle_nl.properties		NOTFOUND
	class LabelsBundle_en_US		NOTFOUND
	file LabelsBundle_en_US.properties	NOTFOUND
	class LabelsBundle_en			NOTFOUND
	file LabelsBundle_en.propertes		OK
	class LabelsBundle			NOTFOUND
	file LabelsBundle.properties		NOTFOUND

Assume we have a .properties file called LabelsBundle_nl_BE.properties and a .properties file called LabelsBundle.properties.

	class LabelsBundle_nl_BE		NOTFOUND
	file LabelsBundle_nl_BE.properties	OK
	class LabelsBundle_nl			NOTFOUND
	file LabelsBundle_nl.properties		NOTFOUND
	class LabelsBundle			NOTFOUND
	file LabelsBundle.properties		OK

In this example, LabelsBundle.properties has become a parent resource bundle of LabelsBundle_nl_BE. You can use the property keys from both these files through the instance that you get back from invoking ResourceBundle.getBundle(…). Also notice that if the resource bundle has been found using the desired locale, the default locale will not be used in looking for a parent. The default locale is only used if locating a bundle with the desired locale failed.

As a last note, you must specify the fully qualified name for the family name (or baseclass) when requesting a resource bundle object. For example, if LabelsBundle_nl_BE.properties is in the package mypackage, you will have to say:

	ResourceBundle.getBundle("mypackage.LabelsBundle", "nl", "BE");