import org.springframework.context.annotation.Profile;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 描述: 配置文件工具类
 *
 * @author pengjie_yao
 * @date 2019/9/9 15:16
 */
public class PropertiesUtils {



    /**
     * 传递键值对的Map,更新properties文件
     * @param fileName 文件名(放在resource源包目录下),需要后缀
     * @param keyValueMap 键值对Map
     */
    public static void updateProperties(String fileName, Map<String, String> keyValueMap) throws Exception {
        //获取文件路径
        String filePath = Profile.class.getClassLoader().getResource(fileName).toURI().getPath();
        System.out.println("propertiesPath:" + filePath);
        Properties props = new Properties();
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            // 从输入流中读取属性列表(键和元素对)
            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            props.load(br);
            br.close();
            // 写入属性文件
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
            // 清空旧的文件
            // props.clear();
            for (String key : keyValueMap.keySet()) {
                props.setProperty(key, keyValueMap.get(key));
                System.out.println("配置文件中要进行修改的key为:"+key);
                System.out.println("修改后的数据为:"+keyValueMap.get(key));
            }
            props.store(bw, "改变数据");
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Visit " + filePath + " for updating " + "" + " value error");
        } finally {
            try {
                br.close();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @Title: getProfileByClassLoader
     * @Description: 采用ClassLoader(类加载器)方式进行读取配置信息
     * @return Map<String,Object> 以Map键值对方式返回配置文件内容
     * @param fileName 配置文件名称
     * 优点:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息
     * 缺点:只能加载类classes下面的资源文件
     */
    public static Map<String, Object> getProfileByClassLoader(String fileName) {
        // 通过ClassLoader获取到文件输入流对象
        InputStream in = Profile.class.getClassLoader().getResourceAsStream(fileName);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        Properties props = new Properties();
        Map<String, Object> profileMap = new HashMap<String, Object>();
        try {
            props.load(reader);
            for (Object key : props.keySet()) {
                profileMap.put(key.toString(), props.getProperty(key.toString()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return profileMap;
    }

}

参考链接:
https://github.com/f763180872...


岁月峥嵘走过
34 声望2 粉丝