java 自定义读取properties配置文件属性

发布时间 2023-08-01 19:24:42作者: 黄大虾

把属性存到一个map里,并提供get方法,如果没有获取到值,则重新加载一遍配置文件,重新赋值,从而刷新数package com.aaa.demo.testProperties;

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

/**
 * projectName: testSpring
 *
 * @author: 
 * time: 2023/8/1 18:11
 * description:
 */
public class TestProPerties {

    private static Map propertiesMap = new HashMap();

    public static void main(String[] args) throws IOException {
        String name = getValue("name");
        System.out.println(name);
    }
/**
     * 获取值,没有值的话会重新从properties配置文件加载一遍
     * @param key
     * @return
     * @throws IOException
     */
    public static String getValue(String key) throws IOException {
        String value = (String) propertiesMap.get(key);

        if (value == null || value.length() < 1) {
            TestProPerties testProPerties = new TestProPerties();
            testProPerties.refresh();
            return (String) propertiesMap.get(key);
        }else {
            return value;
        }
    }


    /**
     * 刷新数据
     * @throws IOException
     */
    public void refresh() throws IOException {

        //获取配置文件,要注意路径问题,路径不对会找不到文件,当前文件在SRC根目录下
        InputStream is = this.getClass().getResourceAsStream("/test11.properties");

        Properties prop= new Properties();
        prop.load(is);
        is.close();

        Enumeration<?> enumeration = prop.propertyNames();
        while (enumeration.hasMoreElements()) {
            String o = (String) enumeration.nextElement();
            propertiesMap.put(o, prop.get(o));
        }
    }
}