The following code snippet will convert a resource bundle into a map object, a key-value mapping. It will read from a file called Messages_en_GB.properties
which corresponding to the Locale.UK
. For example the file contain the following string. This file should be placed under the resources
directory.
welcome.message = Hello World!
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<String, String> map = convertResourceBundleToMap(resource);
// Print the entire contents of the Map.
for (String key : map.keySet()) {
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<String, String> convertResourceBundleToMap(ResourceBundle resource) {
Map<String, String> map = new HashMap<>();
Enumeration<String> keys = resource.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
map.put(key, resource.getString(key));
}
return map;
}
}
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019
1 Comments