How do I use ResourceBundle for i18n?

Category: java.util, viewed: 20193 time(s).

Creating an application for users in different regions can be hard in term of the message format for the local region. Java provide a ResourceBundle class that help internationalize our application.

To create resources for i18n (there are 18 letters between the first i and the final n) we need to create a file for each locale our application supported. The file name must be ended in language_COUNTRY.properties. For instance a resource bundle for Locale.UK will be MessagesBundle_en_GB.properties.

When the bundle has been loaded we can use bundle.getString(key) to read specific message from our resource bundle file.

package org.kodejava.example.util;

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

public class InternationalizationDemo {

    public static void main(String[] args) {
        //
        // Load resource bundle for Locale.UK locale. The resource bundle will 
        // load the MessagesBundle_en_GB.properties file.
        //
        ResourceBundle bundle = ResourceBundle.getBundle("MessagesBundle", Locale.UK);
        System.out.println("Message in " + Locale.UK + ": " + bundle.getString("greeting"));

        //
        // Change the default locale to Indonesian and get the default resource
        // bundle for the current locale.
        //
        Locale.setDefault(new Locale("in", "ID"));
        bundle = ResourceBundle.getBundle("MessagesBundle");
        System.out.println("Message in " + Locale.getDefault() + ": " + bundle.getString("greeting"));
    }
}

Below are some example of our resource bundle files, these files should be located in our application classpath to enable the ResourceBundle class to read it.

MessagesBundle_en_GB.properties
    greeting=Hello, how are you?
MessagesBundle_in_ID.properties
    greeting=Halo, apa kabar?
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats