January 3, 2017

Internationalization (i18n) with ResourceBundle and Properties

To externalize local messages, Java have the java.util.ResourceBundle class.

Create a properties file for the default locale. Then create a new properties for each locale with the suffix _<language>_<COUNTRY>, in the same way you initialize java.util.Locale.Locale(String, String).

Example

messages.properties
messages_sv_SE.properties
messages_en_US.properties

To load the localized text, use java.util.ResourceBundle.getString(String).

Example

messages.properties

hello.label=Hello World!
hello.info=Entered number = %d and string = %s

messages_sv_SE.properties

# Använd UTF-8 encoding för icke ASCII tecken, se t.ex. http://www.utf8-chartable.de/ 
# \u00E5    å
# \u00E4    ä
# \u00F6    ö
# \u00C5    Å
# \u00C4    Ä
# \u00D6    Ö
hello.label=Hall\u00E5 v\u00E4rlden!
hello.info=Entered number = %d and string = %s

And the Java code to load them.

ResourceBundle bundle = ResourceBundle.getBundle("messages");
System.out.println("hello.label : " + bundle.getString("hello.label"));
System.out.println("hello.info : " + String.format(bundle.getString("hello.info"), 2, "en"));

Locale.setDefault(new Locale("sv", "SE"));
ResourceBundle bundleSE = ResourceBundle.getBundle("messages");
System.out.println("hello.label : " + bundleSE.getString("hello.label"));
System.out.println("hello.info : " + String.format(bundleSE.getString("hello.info"), 2, "hej"));

Output

hello.label : Hello World!
hello.info : Entered number = 2 and string = en
hello.label : Hallå världen!
hello.info : Entered number = 2 and string = hej

No comments: