Internalization in Java using ResourceBundle

2009/09/29

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");
}

%d bloggers like this: