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 thegetString(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 thegetString(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.