如何读取yaml(yml)文件
2018-01-16 11:11
399 查看
public class Config { private static final Config CONFIG = new Config("/codes.yml"); private Map<String, Object> root; 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(); } public Object getOj(String key) { Object value = getValue(key); return value; } /** * @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); } } /** * @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; } }
调用:
Config.getConfig().get("key")
相关文章推荐
- springboot如何读取配置文件(application.yml)中的属性值
- 如何使用opencv的c++接口来读取、写结构体数组到yml文件中
- 如何用Spring读取JAR中的文件
- [VB.NET]VB.NET下如何用结构和类实现文件的读取?
- 如何读取sd下的json文件,并解析展示,添加到数据库中
- 如何用python读取和写入TIFF文件2
- 问asp如何读取多个同样节点的xml文件。
- JAVA如何实现读取文件最后一行记录,在文件的结尾追加记录
- IIS7 如何设置读取、脚本和可执行文件的执行权限
- 如何在VB 中读取 UTF-8 格式的文件?
- java如何读取.properties文件下的信息
- 如何读取Hadoop中压缩的文件
- Python如何读取pkl文件
- ExtJS如何读取XML、Json文件
- MATLAB: 如何读取txt中的文件 如何将数据批量写入数据 文件名递增
- 如何读取jar包外的properties文件和log4j.properties
- 如何有效的使用C#读取文件
- c#如何读取配置文件INI
- android 如何设置文件元信息及读取Md5校验码
- [dotNET]如何利用ConfigurationSettings.AppSettings.GetValues读取配置文件中多个同Key的value