Java如何将ResourceBundle转换为Map?
以下代码片段将资源束转换为映射对象,即键-值映射。它将从名为的文件中读取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;
}
}
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便