18.3 Bundling Resources

Locale-specific data (messages, labels, colors, images, etc.) must be customized according to the conventions and customs for each locale that an application wishes to support. A resource bundle is a convenient and efficient way to store and retrieve locale-specific data in an application. The abstract class java.util.ResourceBundle is the key to managing locale-specific data in a Java application.

Resource Bundle Families

A resource bundle essentially defines key–value pairs that are associated with a specific locale. The synonyms resources and properties are also used for key–value pairs, depending on how a resource bundle is implemented. The application can retrieve locale-specific resources from the appropriate resource bundle.

A specific naming convention is used to create resource bundles. This naming convention allows resource bundles to be associated with specific locales, thereby defining resource bundle families. All bundles in a resource bundle family have a common base name, along with other locale-specific extensions, but the language and country extensions are the important ones to consider. Best practice is to use the following name for a resource bundle that defines all country-specific resources:

Click here to view code image

baseName_languageCode_countryCode

and to use the following name for a resource bundle that defines all language-specific resources:

baseName_languageCode

In addition, it is also recommended to include a default resource bundle that has only the common base name. The underscore (_) is mandatory. The extensions with the language and country codes are according to locale conventions discussed earlier (p. 1096). The following resource bundle family, used in Example 18.3, has the common base name BasicResources:

Click here to view code image

BasicResources            
Default resource bundle
BasicResources_no_NO     
Resource bundle for Norwegian (Norway) locale
BasicResources_fr        
Resource bundle for all locales with French language

An application need not store all resources associated with a locale in a single resource bundle family. The resources can be organized in different resource bundle families for a given locale.

This naming scheme allows a resource bundle to be associated with a specific locale. Note that an application provides a version of each resource bundle for every locale supported by the application, unless they are shared. An example of such sharing is shown above: the locales for France and French-Canada both share the BasicResources_fr resource bundle. We have not defined separate BasicResources bundles for these two locales. We will have more to say on this matter later when we discuss how resources are located for a given locale in a resource bundle family.

Leave a Reply

Your email address will not be published. Required fields are marked *