Home » Java Codes

Java Utility Classes – Load a Resource Bundle

6 March 2009 326 views No Comment

This example shows how to load a ResourceBundle from the classpath and then enumerate through it.
Since ResourceBundle is an abstract class and therefore cannot be instantiated we call its static method getBundle() which returns the ResourceBundle instance.
The method has a few overloads but we use the one that takes a basename (in this case ‘Phrases’) and a locale. This means that somewhere on the classpath there has to be a file named ‘Phrases_en_US.properties’.
In this example the file only has two rows (see further below). An Enumeration with the keys is obtained by calling the getKeys() method, then a while-loop is used to enumerate through the keys and print out each of them along with the value.

package com.javadb.examples;

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


/**
 *
 * @aut*#104;o*#114; *#119;w*#119;.*#106;*#97;vadb.*#99;om
 */

public class Main {
    
    public void loadResourceBundle() {
        
        ResourceBundle resource = ResourceBundle.getBundle(“Phrases”, Locale.US);
        
        Enumeration<String> keys = resource.getKeys();
        
        String key = null;
        while (keys.hasMoreElements()) {
            
            key = keys.nextElement();
            
            System.out.println(key ” – “ resource.getObject(key));
        }
    }

 
    public static void main(String[] args) {

        new Main().loadResourceBundle();
    }
 
 }


This is what the contents of the Phrases_en_US.properties file looks like:


phrase1=Hello
phrase2=World


…and this is what the output looks like when the example is run:


phrase2 – World
phrase1 – Hello


Tags: , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave your response!

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>