【小工具】Properties解析器 —— PropertiesParser

在这里插入图片描述

需求 分析:

在我们使用框架的时候,很多配置都是通过properties配置文件进行配置的
那么,到底是如何将这些配置加载到程序中去的呢?
这就利用到了 和 本篇博文的主题相似的工具


代码 实现:

package edu.youzg.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * properties文件 解析器
 * 
 * @author Youzg
 */
public class PropertiesParser {
    private static final Map<String, String> pool;  // 存储从配置文件中读取到的 键值对

    static {
        pool = new HashMap<>();
    }

    public PropertiesParser() {
    }

    /**
     * 加载指定的properties文件
     * @param filePath properties文件 的路径
     */
    public static void loadProperties(String filePath) {
        InputStream is = PropertiesParser.class.getResourceAsStream(filePath);
        Properties property = new Properties();
        try {
            property.load(is);

            Enumeration<Object> keys = property.keys();
            while (keys.hasMoreElements()) {
                String key = (String) keys.nextElement();
                String value = property.getProperty(key);

                pool.put(key, value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据 键名,获取 解析结果的 值
     * @param key 键名
     * @return 对应的值
     */
    public static String value(String key) {
        return pool.get(key);
    }

}

posted @ 2020-04-21 23:50  在下右转,有何贵干  阅读(134)  评论(0编辑  收藏  举报