You are on page 1of 2

http://tutorials.jenkov.com/java-internationalization/resourcebundle.

html

The ResourceBundle class has two subclasses called PropertyResourceBundle and ListResourceBundle.

All interaction with these two subclasses goes through the ResourceBundle class.

Creating a ResourceBundle

 First you need a Locale instance.


 Then you pass that Locale instance to the ResourceBundle.getBundle() method along with the
name of the resource bundle to load.
 Finally you can access the localized values in the ResourceBundle via its different
[getString()/getObject()] methods.

Locale locale = new Locale("en", "US");


ResourceBundle labels = ResourceBundle.getBundle("jenkov.Property.MyBundle", locale);
System.out.println(labels.getString("label1"));

You never create ResourceBundle instance directly, but an instance of one of its two subclasses.

Both are created using the above factory method.

First the ResourceBundle class will look for a ListResourceBundle, and then for a PropertyResource
Bundle.

It does so by matching the name of the requested resource bundle (first parameter in the getBundle()
method) against the class names of a ListResourceBundle or a property file resource bundle.

Passing parameters to the message:

This is achieved using message-format i.e java.text.MessageFormat class;

ResourceBundle bundle = ResourceBundle.getBundle("MyClassBundle", currentLocale);


String message = bundle.getString("currency");

MessageFormat messageFormat = new MessageFormat("");


messageFormat.setLocale(currentLocale);
messageFormat.applyPattern(message);
Object[] messageArguments = { "This is not localized", new Integer(3)};
// Argument passed to the message
String result = messageFormat.format(messageArguments);

Where currentLocale and message is defined as:


Locale currentLocale = new Locale("de", "DE");
And message is
Currency = "EUR {0} is {1}”

OUTPUT:
EUR This is not localized is 3

Conclusion:
{0} is first field of messageArguments[]
{1} is second field of messageArguments[] and so on.
messageArguments[] can have more fields than actual message.
Notice, messages present in PropertyResourceBundle or ListResourceBundle can be localized. Argument
passed from java-code (i.e. messageArguments) can’t be localized. Because we have presentation of
Property/List ResourceBundle in different languages in the form of Choice_en_US.properties or
Choice_fr_FR.properties. Argument passed can’t have such corresponding local representation.
So if something need to be localized then it need to be removed from argument and put into property
or list files.

You might also like