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.
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 Howcodex.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 Howcodex.COM!
Here you can figure out that the key is same but the value is locale specific in both the properties file.
Create ResourceBundle object with properties file name and locale using following syntax.
ResourceBundle bundle = ResourceBundle.getBundle("Messages", Locale.US);
Get the value from ResourceBundle object by passing the key.
String value = bundle.getString("message");
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")); } }
It will print the following result.
Message in en_US: Welcome to Howcodex.COM! Message in fr_FR: Bienvenue sur Howcodex.COM!
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.