Java Cookbook
Resource Bundles
One of the first steps in internationalizing an application is th externalizing of text. This simplifies the translation process and makes localization far easier.
The standard way of handling resources in Java has been by the use of properties files. A properties file is simply a text file containing key value pairs. It is named with the syntax, name_language_country_variant.properties. So a bundle for a Japanese bundle called errors would be titled, errors_ja.properties.
An example file might look like:
firstName=First Name
lastName=Last Name
There are a few limitations of properties files. The biggest problem is that they are not Unicode encoded. This means that many characters, like Japanese or Chinese double-byte, will need to be escaped in the properties files. This makes them un-readable to the common user. The native2ascii tool packaged with Java can convert your unicode to ascii for you.
To load a resource bundle and retrieve a key from it:
ResourceBundle rb = PropertyResourceBundle.getBundle("com.cookbook.bundles.foo");
System.out.println(rb.getString("firstName"));
To load a resource bundle for a particular locale if available:
Locale en = Locale.ENGLISH;
ResourceBundle rb = PropertyResourceBundle.getBundle("com.cookbook.bundles.foo", en);
System.out.println(rb.getString("firstName"));
If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.
This site is ad supported. I hope you find something among our sponsors worth clicking. ;)
i18n search