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;
}
}
热门推荐
10 麻将打牌祝福语简短霸气
11 看望长辈礼物祝福语简短
12 毕业祝福语小长句简短
13 情侣签名简短英文祝福语
14 同事提前喝酒祝福语简短
15 送你妹妹新婚祝福语简短
16 毕业祝福语贺词大全简短
17 长辈生日欢快祝福语简短
18 祝福语朋友简短恋爱结婚