The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.text  [26 examples]

e310. Localizing Messages

Messages and text string should be localized in a resource bundle. There are several types of resource bundles. This example demonstrates how to use a property-file type resource bundle. Here are two examples of resource files:

MyResources_en.properties:

    hello=Hello
    bye=Goodbye
MyResources_fr.properties:
    hello=Bonjour
    bye=Au Revoir
When loading a property-file resource bundle, a base name and desired locale is specified. The system then looks in the classpath for a file whose name matches one of the following patterns in order:
    
basename_locale.properties
    basename.properties
    basename_defaultLocale.properties
For example, given the base name MyResources, a locale of fr, and a default locale of en, the system first looks for
    MyResources_fr.properties
    MyResources.properties
    MyResources_en.properties
Here's an example that loads a resource bundle:
    String baseName = "MyResources";
    try {
        // Get the resource bundle for the default locale
        ResourceBundle rb = ResourceBundle.getBundle(baseName);
    
        String key = "hello";
        String s = rb.getString(key); // Hello
        key = "bye";
        s = rb.getString(key);        // Goodbye
    
        // Get the resource bundle for a specific locale
        rb = ResourceBundle.getBundle(baseName, Locale.FRENCH);
    
        key = "hello";
        s = rb.getString(key);        // Bonjour
        key = "bye";
        s = rb.getString(key);        // Au Revoir
    } catch (MissingResourceException e) {
        // The resource bundle cannot be found or
        // the key does not exist in the resource bundle
    }

 Related Examples
e305. Determining the Type of a Character
e306. Comparing Strings in a Locale-Independent Way
e307. Iterating the Characters of a String
e308. Adding an Attribute to a String
e309. Incrementing a Double by the Smallest Possible Amount

See also: Dates    Messsages    Numbers    Times    Words and Sentences   


© 2002 Addison-Wesley.