Load a Resource Bundle


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;


/**
 *
 * @author www.javadb.com
 */

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

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: