Internalization in Java using ResourceBundle

In order to implement localization in your Java application, you can use ResourceBundle and PropertyResourceBundle classes, as following:

Step 1: Create a method that receives a string key for which you need the “translation”:

public String getI18NString(String key) {
    if (key == null)
        return "[" + key + "]";;
    
    try {
        PropertyResourceBundle resBundle = (PropertyResourceBundle) ResourceBundle.getBundle("localization");
        return resBundle.getString(key);
    } catch (Exception e) {
    }
    
    return "[" + key + "]";
}

Step 2: Add localization files to your project, under a source folder. The default translations will be grouped under a file named like localization.properties, the additional languages will use files like localization_fr_FR.properties or localization_de_DE.properties:

01InternalizationInJavaLocalizationFiles

The content of such a file will be as following:

BTN_OK=Approuver
BTN_CANCEL=Annuler

Step 3: Test the implemented method:

@Test
public void testI18N() {
    assertEquals(getI18NString("BTN_CANCEL"), "Cancel");
    Locale.setDefault(new Locale("ro", "RO"));
    assertEquals(getI18NString("BTN_CANCEL"), "Anuleaza");
    Locale.setDefault(new Locale("fr", "FR"));
    assertEquals(getI18NString("BTN_CANCEL"), "Annuler");
}
Advertisements

One Response to Internalization in Java using ResourceBundle

  1. […] Internalization in Java using ResourceBundle Tue Sep 29, 2009 13:01 pm In order to implement localization in your Java application, you can use ResourceBundle and PropertyResourceBundle classes… […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: