Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说如何读取yaml(yml)文件,希望能够帮助你!!!。
public class Config {
//resource文件夹下的yml文件名
private static final Config CONFIG = new Config("/codes.yml");
private Map<String, Object> root;
/**
* 对工程的yml文件读取处理
* @return
*/
private Config(String... fileNames) {
Map<String, Object> map = new HashMap<String, Object>(0);
for (String fileName : fileNames) {
Map<String, Object> conf = this.getRoot(fileName);
map = this.marge(map, conf);
}
root = map;
}
/**
* 返回对象文件
* @return
*/
public static Config getConfig() {
return CONFIG;
}
/**
* 获取值
* @param key
* @return
*/
private Object getValue(String key) {
Object value = root.get(key);
if (value == null) {
throw new RuntimeException(String.format(
"The value corresponding to the key is not set.key[%s]",
key));
}
return value;
}
/**
* 获取字符串类型数据
* @param key
* @return
*/
public String get(String key) {
Object value = getValue(key);
return value.toString();
}
/**
* 获取yml文件中对象类型的数据
* @param key
* @return
*/
public Object getOj(String key) {
Object value = getValue(key);
return value;
}
/**
* 读取工程resouce下所有的yml文件
* @param resouce
* @return
*/
@SuppressWarnings("unchecked")
private Map<String, Object> getRoot(String resouce) {
InputStream in = null;
try {
in = Config.class.getResourceAsStream(resouce);
return (Map<String, Object>) Yaml.load(in);
} catch (Exception err) {
throw new RuntimeException(
"It failed in reading the configuration file.", err);
}
}
/**
* 判断两个文件中是否有相同的key值
* @param map1
* @param map2
* @return
*/
private Map<String, Object> marge(Map<String, Object> map1,
Map<String, Object> map2) {
Map<String, Object> marged = new HashMap<String, Object>(map1);
for (String key : map2.keySet()) {
if (marged.containsKey(key)) {
throw new RuntimeException(String.format(
"The key overlaps. [%s]", key));
}
marged.put(key, map2.get(key));
}
return marged;
}
}
调用:
1.获取字符串对象
Config.getConfig().get("KEY")
数据格式:
KEY: "key"
2.获取对象
例 List<Map<String, String>>
Object oj = Config.getConfig().getOj("MapList")
//转换成yml文件中读取的数据类型
List<HashMap<String, String>> mapList = (List<HashMap<String, String>>) oj;
//循环读取
for (int i = 0; i < mapList .size(); i++) {
String value= mapList .get(i).get("value");
String key= mapList .get(i).get("key");
System.out.println("value:" + value + " key:" + key)
}
数据格式:
MapList:
- !code {key: "1", value: "test1"}
- !code {key: "2", value: "test2"}
例 List<String>
Object oj = Config.getConfig().getOj("LIST")
//转换成yml文件中读取的数据类型
List<String> list = (List<String>) oj;
//循环读取
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i))
}
数据格式:
LIST:
- listValue1
- listValue2
今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
上一篇
已是最后文章
下一篇
已是最新文章