Sample of retrieving locale-specific data
list of resource bundles:
ButtonLabel
ButtonLabel_de
ButtonLabel_en_GB
ButtonLabel_fr_CA_UNIX
selecting the locale-specific ButtonLabel resource bundle:
Locale currentLocale = new Locale("fr", "CA", "UNIX");
ResourceBundle introLabels =
ResourceBundle.getBundle("ButtonLabel", currentLocale);
2 Types of ResourceBundle
- PropertyResourceBundle - uses a properties file to contain the key-value pairs. The value can only be a String.
properties files for 3 resource bundles:
LabelsBundle.properties
LabelsBundle_de.properties
LabelsBundle_fr.properties
resource bundle sample content:
# This is the LabelsBundle_de.properties file
s1 = Computer
s2 = Platte
s3 = Monitor
s4 = Tastatur
use of resource bundle sample:
Locale[] supportedLocales = {
Locale.FRENCH,
Locale.GERMAN,
Locale.ENGLISH
};
for (int i = 0; i < supportedLocales.length; i ++) {
ResourceBundle labels =
ResourceBundle.getBundle("LabelsBundle",currentLocale);
String value = labels.getString(key);
Enumeration bundleKeys = labels.getKeys();
while (bundleKeys.hasMoreElements()) {
String key = (String)bundleKeys.nextElement();
String value = labels.getString(key);
}
} - ListResourceBundle - uses a list to contain the key-value pairs. The value can be any object.
3 resource bundles:
StatsBundle_en_CA.class
StatsBundle_fr_FR.class
StatsBundle_ja_JP.class
resource bundle sample:
import java.util.*;
public class StatsBundle_ja_JP extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
private Object[][] contents = {
{ "GDP", new Integer(21300) },
{ "Population", new Integer(125449703) },
{ "Literacy", new Double(0.99) },
};
}
use of resource bundle sample:
Locale[] supportedLocales = {
new Locale("en","CA"),
new Locale("ja","JP"),
new Locale("fr","FR")
};
for (int i = 0; i < supportedLocales.length; i ++) {
ResourceBundle stats =
ResourceBundle.getBundle("StatsBundle",currentLocale);
Integer gdp = (Integer)stats.getObject("GDP");
}
Notes:
- things to check/consider when internationalizing: http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html
- numbers, dates, times, or currencies need not be isolated in a ResourceBundle because only the display format of these objects varies with Locale, the objects themselves do not
- it is better to have multiple ResourceBundle by determining related objects and grouping them together
- ResourceBundle.Control class provides a way to control the instantiation and location of resource bundles. You can override its methods to behave differently.
- list of language codes (ISO-639): http://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txt
- list of country codes (ISO-3166): http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
Source: http://java.sun.com/docs/books/tutorial/i18n/resbundle/index.html
No comments:
Post a Comment