How do I convert ResourceBundle to Map?

package org.kodejava.example.util;

import java.util.*;

public class ResourceBundleToMap {
    public static void main(String[] args) {
        //
        // Load resource bundle Messages_en_GB.properties from the classpath.
        //
        ResourceBundle resource = ResourceBundle.getBundle("Messages", Locale.UK);

        //
        // Call the convertResourceBundleTopMap method to convert the resource
        // bundle into a Map object.
        //
        Map map = convertResourceBundleToMap(resource);

        //
        // Print the entire contents of the Map.
        //
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            String value = map.get(key);
            System.out.println(key + " = " + value);
        }
    }

    /**
     * Convert ResourceBundle into a Map object.
     *
     * @param resource a resource bundle to convert.
     * @return Map a map version of the resource bundle.
     */
    private static Map convertResourceBundleToMap(ResourceBundle resource) {
        Map map = new HashMap();

        Enumeration keys = resource.getKeys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            map.put(key, resource.getString(key));            
        }
        
        return map;
    }
}

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

1 Comments

Leave a Reply