util

ResourceBundle for I18N messages example

With this example we are going to demonstrate how to use the ResourceBundle for I18N messages. ResourceBundle can be used to provide us with locale-specific resources. In short, to use the ResourceBundle for I18N messages you should:

  • Load resource bundle for locale Locale.US, with the getBundle(String baseName, Locale locale) API method of the ResourceBundle and then the getString(String key) API method of the ResourceBundle.
  • Change the default locale to Greek, with the setDefault(Locale newLocale) API method of the Locale.
  • Get the resource bundle for the new locale, with the getBundle(String baseName) API method and then the getString(String key) API method of the ResourceBundle.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

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

public class ResourceBundleExample {

    public static void main(String[] args) {


  // Load resource bundle for locale Locale.US

  // ResourceBundle_en_US.properties file will be used

  ResourceBundle resourceBundle = ResourceBundle.getBundle("ResourceBundle", Locale.US);

  System.out.println("Message in " + Locale.US + " : " + resourceBundle.getString("sayHello"));


  // Change the default locale to Greek and get the resource bundle for that locale

  // ResourceBundle_el_GR.properties file will be used

  Locale.setDefault(new Locale("el", "GR"));

  resourceBundle = ResourceBundle.getBundle("ResourceBundle");

  System.out.println("Message in " + Locale.getDefault() + " : " + resourceBundle.getString("sayHello"));

    }

}

The files used are those shown below :

ResourceBundle_en_US.properties

sayHello=Hello, world!

ResourceBundle_el_GR.properties

sayHello=u0393u03b5u03b9u03b1 u03bau03b1u03b9 u03c7u03b1u03c1u03ac!

Output:

Message in en_US : Hello, world!
Message in el_GR : Γεια και χα�ά!

 
This was an example of how to use the ResourceBundle for I18N messages in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button