Java Programming Tutorials

Java programming tutorials with many code examples!

Java ResourceBundle – internationalized program

Java ResourceBundle internationalize program

In this tutorial we’re going to implement a simple dictionary to show how to use Resourcebundle to internationalize program in an easy way.

I18n dictionary using ResourceBundle

package com.farenda.java.util;

import java.util.Locale;
import java.util.ResourceBundle;

import static java.util.ResourceBundle.getBundle;

public class ResourceBundleExample {

    private static final String BUNDLE_NAME
            = "com.farenda.java.util.Words";

    public static void main(String[] args) {
        Locale.setDefault(Locale.ENGLISH);

        displayWord("book", Locale.getDefault());
        displayWord("book", Locale.JAPAN);
        displayWord("book", new Locale("pl", "PL"));
        displayWord("book", new Locale("eo"));
    }

    private static void displayWord(String word, Locale locale) {
        ResourceBundle words = getBundle(BUNDLE_NAME, locale);
        System.out.printf("'%s' in locale '%s': %s%n",
                word, locale, words.getString(word));
    }
}

When run, the above program will print the following:

'book' in locale 'en': book
'book' in locale 'ja_JP': book
'book' in locale 'pl_PL': książka
'book' in locale 'eo': libro

We don’t have ResourceBundle for the Japanese locale, so it falls back to the default, which is English here. Also note that we create locale pl_PL, but the matched file with translations is Words_pl.properties – this was the closest match.

Properties files with translations

We need to create a set of properties files in the path used in BUNDLE_NAME. Here it is com.farenda.java.util package and the files should start with Words base name. After the base name you can add language prefix and then, optionally, country code. Full name can consists of:

baseName + "_" + language + "_" + script + "_" + country + "_" + variant
or
baseName + "_" + language + "_" + country + "_" + variant

Words.properties for default English locale:

book=book

Words_pl_PL.properties for Polish locale (note that we need to escape diacritics):

book=ksi\u0105\u017cka

And Words_eo.properties for Esperanto language:

book=libro
Share with the World!