使用文件中的数据填充 java 哈希图
populate a java hashmap with data from file
我有以下数据结构:
"properties": {
"P6": "head of government",
"P7": "brother",
"P9": "sister",
"P10": "video",
"P14": "highway marker",
"P15": "road map",
"P16": "highway system",
"P17": "country",
"P18": "image",
"P19": "place of birth",
"P20": "place of death",
"P21": "sex or gender",
...
我想从文件中读取它并用它来填充 Map<String,String>
.
类型的哈希映射
我试过用gson做这个但是没有成功,我觉得一定有更简单的方法。
也许我应该读入它并使用模式匹配器或正则表达式将其拆分?
这是我一直在使用的代码:
/*
* P values file
*/
String jsonTxt_P = null;
File P_Value_file = new File("properties-es.json");
//raed in the P values
if (P_Value_file.exists())
{
InputStream is = new FileInputStream("properties-es.json");
jsonTxt_P = IOUtils.toString(is);
}
//
Gson json_P = new Gson();
Map<String,String> massive_P_storage_map = new HashMap<String,String>();
massive_P_storage_map = (Map<String,String>) json_P.fromJson(jsonTxt_P, massive_Q_storage_map.getClass());
System.out.println(massive_P_storage_map);
这样做
BufferedReader reader = new BufferedReader(new FileReader(new File("properties-es.json")));
Map<String, HashMap<String, Object>> map =
new Gson().fromJson(reader, new TypeToken<HashMap<String, HashMap<String, Object>>>() {}.getType());
这是根据键名获取值的方法
String value = (String) map.get("properties").get("P6");
System.out.println(value);
我有以下数据结构:
"properties": {
"P6": "head of government",
"P7": "brother",
"P9": "sister",
"P10": "video",
"P14": "highway marker",
"P15": "road map",
"P16": "highway system",
"P17": "country",
"P18": "image",
"P19": "place of birth",
"P20": "place of death",
"P21": "sex or gender",
...
我想从文件中读取它并用它来填充 Map<String,String>
.
我试过用gson做这个但是没有成功,我觉得一定有更简单的方法。
也许我应该读入它并使用模式匹配器或正则表达式将其拆分?
这是我一直在使用的代码:
/*
* P values file
*/
String jsonTxt_P = null;
File P_Value_file = new File("properties-es.json");
//raed in the P values
if (P_Value_file.exists())
{
InputStream is = new FileInputStream("properties-es.json");
jsonTxt_P = IOUtils.toString(is);
}
//
Gson json_P = new Gson();
Map<String,String> massive_P_storage_map = new HashMap<String,String>();
massive_P_storage_map = (Map<String,String>) json_P.fromJson(jsonTxt_P, massive_Q_storage_map.getClass());
System.out.println(massive_P_storage_map);
这样做
BufferedReader reader = new BufferedReader(new FileReader(new File("properties-es.json")));
Map<String, HashMap<String, Object>> map =
new Gson().fromJson(reader, new TypeToken<HashMap<String, HashMap<String, Object>>>() {}.getType());
这是根据键名获取值的方法
String value = (String) map.get("properties").get("P6");
System.out.println(value);