Java Internalization - ResourceBundle Class


Advertisements

ResourceBundle class is used to store text and objects which are locale sensitive. Generally we use property files to store locale specific text and then represent them using ResourceBundle object. Following are the steps to use locale specific properties file in a java based application.

Step 1: Create properties files.

Suppose we need properties file for English locale. Then create a properties file name XXX_en_US.properties where XXX is the name of the file and en_US represents the locale for English(US).

Messages_en_US.properties

message=Welcome to TutorialsPoint.COM!

Let's now create properties file for French locale. Then create a properties file name XXX_fr_FR.properties where XXX is the name of the file and fr_FR represents the locale for French(France).

Messages_fr_FR.properties

message=Bienvenue sur TutorialsPoint.COM!

Here you can figure out that the key is same but the value is locale specific in both the properties file.

Step 2: Create ResourceBundle object

Create ResourceBundle object with properties file name and locale using following syntax.

ResourceBundle bundle = ResourceBundle.getBundle("Messages", Locale.US);

Step 3: Get the value from ResourceBundle object.

Get the value from ResourceBundle object by passing the key.

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

Example

Following example illustrate the use of ResourceBundle objects to display locale specific values from properties files.

IOTester.java

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

public class I18NTester {
   public static void main(String[] args) {
      ResourceBundle bundle = ResourceBundle.getBundle("Messages", Locale.US);  
      System.out.println("Message in "+Locale.US +": "+bundle.getString("message"));  

      bundle = ResourceBundle.getBundle("Messages", Locale.FRANCE);  
      System.out.println("Message in "+Locale.FRANCE +": "+bundle.getString("message"));
   }
}

Output

It will print the following result.

Message in en_US: Welcome to TutorialsPoint.COM!
Message in fr_FR: Bienvenue sur TutorialsPoint.COM!

Notes for Naming Conventions

Following are the naming conventions for the properties file.

  • For properties file mapped to default locale, no prefix is mandatory. message_en_US.properties is equivalent to message.properties.

  • For properties file mapped to locale, prefix can be attached in two ways. message_fr.properties is equivalent to message_fr_FR.properties.

Print
Advertisements