Creating a Resource Bundle

Problem

You need to create a resource bundle for use by I18N.

Solution

A resource bundle is just a collection of names and values. You can write a java.util.ResourceBundle subclass, but it is easier to create them as textual Properties files (see Section 7.8), which you then load with ResourceBundle.getBundle( ). The files can be created using any text editor. Leaving it in a text file format also allows user customization; a user whose language is not provided for, or who wishes to change the wording somewhat due to local variations in dialect, will have no trouble editing the file.

Note that the resource bundle text file should not have the same name as any of your Java classes. The reason is that the ResourceBundle constructs a class dynamically, with the same name as the resource files. You can confirm this by running java -verbose on any of the programs that use the I18N class from this chapter.

Discussion

Here is a sample for a simple browser (see the MenuIntl program in Section 14.12):

# Default Menu properties
# The File Menu
file.label=File Menu
file.new.label=New File
file.new.key=N

Creating the default properties file will usually not be a problem, but creating properties files for other languages might. Unless you are a large multinational corporation, you will probably not have the resources (pardon the pun) to create resource files in-house. If you are shipping commercial software, you need to identify your target markets and understand which ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.