Wednesday 6 August 2014

How to read a properties file with a Resource Bundle

A ResourceBundle offers a very easy way to access key/value pairs in a properties file in a Java.
ResourceBundle class is used to internationalize the messages. In other words, we can say that it provides a mechanism to globalize the messages.

The hardcoded message is not considered good in terms of programming, because it differs from one country to another. So we use the ResourceBundle class to globalize the massages. The ResourceBundle class loads these informations from the properties file that contains the messages.


Conventionally, the name of the properties file should be filename_languagecode_country code for example MessageBundle_en_US.properties.



Here is the Example:

Create the below properties file and place in Classpath.

MessageBundle_en_US.properties
greeting=Hello, how


MessageBundle_fr_FR.properties
greeting=Bonjour



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

public class InternationalizationExample {

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


        Locale.setDefault(new Locale("fr", "FR"));
        bundle = ResourceBundle.getBundle("MessageBundle");
        System.out.println("Message in "+Locale.getDefault()+":"+bundle.getString("greeting"));

    }


}


Out Put:


Message in en_US:Hello
Message in fr_FR:Bonjour







No comments:

Post a Comment