package thyyxxk.webserver.utils;

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

public class PropertiesUtil {
    private static final HashMap<String, Properties> dbMap = new HashMap<>();

    public static Properties get(String name) {
        Properties properties = dbMap.get(name);
        if (null == properties) {
            properties = getProperties(name);
            dbMap.put(name, properties);
        }
        return properties;
    }


    /**
     * 按key获取值
     */
    static String readProperty(String properiesName, String key) {
        String value = "";
        InputStream is = null;
        try {
            is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);
            Properties p = new Properties();
            p.load(is);
            value = p.getProperty(key);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }

    /**
     * 获取整个配置信息
     */
    static Properties getProperties(String properiesName) {
        Properties p = new Properties();
        InputStream is = null;
        try {
            is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);
            p.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return p;
    }

}
