Java ListResourceBundle tutorial
In this tutorial we’re going to show how to use Java ListResourceBundle to make you program speak in different languages.
ListResourceBundle subclass
In the following code we’re going to provide translations for Esperanto language.
Notice that unlike full implementation of ResourceBundle subclass we have to implement only one method:
- Object[][] getContents()
Not three (see Extending ResourceBundle):
- handleGetObject(String key),
- handleKeySet(),
- getKeys().
package com.farenda.java.util; import java.util.ListResourceBundle; public class Numbers_eo extends ListResourceBundle { private static final Object[][] TRANSLATIONS = { {"sum-of-numbers", "%s plus %s estas %s"}, {"one", "unu"}, {"two", "du"}, {"three", "tri"} }; @Override protected Object[][] getContents() { return TRANSLATIONS; } }
Important: make the class thread-safe if plan to use it concurrently!
Use of ListResourceBundle
Here we’ll load the resource bundle using static ResourceBundle.getBundle(String, Locale) method, take localized messages from it and display them:
private static final String BUNDLE_NAME = "com.farenda.java.util.Numbers"; public static void main(String[] args) { ResourceBundle bundle = getBundle(BUNDLE_NAME, new Locale("eo")); translate(bundle, "one"); translate(bundle, "two"); translate(bundle, "three"); System.out.printf( bundle.getString("sum-of-numbers"), bundle.getString("one"), bundle.getString("two"), bundle.getString("three")); } static void translate(ResourceBundle bundle, String key) { System.out.printf("'%s' in Esperanto: %s%n", key, bundle.getString(key)); }
And here’s the result of running the example:
'one' in Esperanto: unu 'two' in Esperanto: du 'three' in Esperanto: tri unu plus du estas tri
Remember that bundle name have to be full path to resource bundle!
References:
- Intro to ResourceBundles in Java
- ResourceBundle direct subclass
Checkout for more examples and how to mix class-based ResourceBundles with property-based ones.