Creating Resource Bundles – Localization
By Gigi Rosen / February 24, 2023 / No Comments / Conditional Formatting, Oracle Certifications, The ZonedDateTime Class
Creating Resource Bundles
A resource bundle can be a property resource file (as shown in Example 18.2) or a resource bundle class, which is a subclass of the abstract class java.util.ResourceBundle. A resource bundle class can be used to implement resources that are not strings. We will not discuss resource bundle classes here as they are beyond the scope of this book.
Property Resource Files
A property resource file is a properties file, in which each line defines a key–value pair that designates a property. The discussion on properties files (p. 1100) also applies to a property resource file. However, note that a property resource file must be named according to the resource bundle naming scheme outlined above, and has the mandatory file extension .properties in addition.
Example 18.2 shows the three property resource files used by Example 18.3. The property resource file BasicResources.properties defines the default resource bundle for the resource bundle family BasicResources that applies for all locales. The property resource files BasicResources_no_NO.properties and BasicResources_fr.properties define resource bundles for the Norwegian (Norway) locale and the French locale, respectively. Note the appending of the language/country code to the bundle family name using the underscore (_).
The first line in each of the three property resource files in Example 18.2 is a comment documenting the name of the file. Typically, the property resource files are placed in a directory, usually called resources, which is in the same location as the application.
Note also that we use the same key name for a property in all property resource files of a resource bundle family. The greeting, gratitude, and the farewell messages are designated by their respective key names in all property resource files. In Example 18.2, the astute reader will notice that the key name company is only specified in the default property resource file BasicResources.properties, but not in the other property resource files. If the default resource bundle for a resource bundle family is provided, it is always in the search path when locating the value associated with a key.
Modifying an existing property resource file or adding a new property resource file may not require recompiling of the application, depending on the implication of the changes made to the property resource file.
Example 18.2 The BasicResources Bundle Family (See Also Example 18.3)
# File: BasicResources.properties
company = GLOBUS
greeting = Hi!
gratitude = Thank you!
farewell = See you!
# File: BasicResources_no_NO.properties
greeting = Hei!
gratitude = Takk!
farewell = Ha det!
Click here to view code image # File: BasicResources_fr.properties
greeting = Bonjour!
gratitude = Merci!
farewell = Au revoir!