以下代码片段将资源束转换为映射对象,即键-值映射。它将从名为的文件中读取Messages_en_GB.properties对应于的文件Locale.UK。例如,文件包含以下字符串。该文件应放在resources目录下。
welcome.message = Hello World!
package org.nhooo.example.util;
import java.util.*;
public class ResourceBundleToMap {
public static void main(String[] args) {
// 从类路径加载资源包Messages_en_GB.properties。
ResourceBundle resource = ResourceBundle.getBundle("Messages", Locale.UK);
// 调用convertResourceBundleTopMap方法转换资源
// 捆绑成一个Map对象。
Map<String, String> map = convertResourceBundleToMap(resource);
// 打印映射的全部内容。
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;
}
}