如何读取yaml(yml)文件

public class Config {
    private static final Config CONFIG = new Config("/codes.yml");

    private Map root;

    private Config(String... fileNames) {
        Map map = new HashMap(0);
        for (String fileName : fileNames) {
            Map 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 getRoot(String resouce) {
        InputStream in = null;
        try {
            in = Config.class.getResourceAsStream(resouce);
            return (Map) Yaml.load(in);
        } catch (Exception err) {
            throw new RuntimeException(
                    "It failed in reading the configuration file.", err);
        }
    }

    /**
     * @param map1
     * @param map2
     * @return
     */
    private Map marge(Map map1,
            Map map2) {

        Map marged = new HashMap(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")


你可能感兴趣的:(java)