首页 > 其他分享 >application.yml与application.properties文件的相互转换、属性提取

application.yml与application.properties文件的相互转换、属性提取

时间:2022-12-02 13:24:24浏览次数:43  
标签:Map return String yml application key new properties

package com.liftsail.testprofiledemo.utiltest;

import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @Author: liftsail
 * @Date: 2022/12/2 10:15
 * @Description: 不积跬步无以至千里
 * 把properties 转化为 Map
 */
public class PropertiesToMapUtil {

    /**
     * properties 配置文件转Map 集合
     *
     * @param properties
     * @return
     */
    public static Map<String, Object> prop2Map(Properties properties) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            Map<String, Object> propMap = new HashMap<>();
            for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                propMap.put((String) entry.getKey(), entry.getValue());
            }
            resultMap = parseToMap(propMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 将propMap 转化为 HashTable结构
     *
     * @param propMap
     * @return
     */
    private static Map<String, Object> parseToMap(Map<String, Object> propMap) {
        Map<String, Object> resultMap = new Hashtable<>();
        try {
            if (CollectionUtils.isEmpty(propMap)) {
                return resultMap;
            }
            Iterator<Map.Entry<String, Object>> it = propMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                String key = entry.getKey();
                Object propValue = entry.getValue();
                Object resultObj = null;
                if (!key.contains(".")) {
                    if (!key.contains("[") && !key.contains("]")) {
                        resultMap.put(key, propValue);
                    } else if (key.contains("[") && key.contains("]")) {
                        key = key.substring(0, key.lastIndexOf("["));
                        resultObj = resultMap.get(key);
                        List<String> list = null;
                        if (resultObj != null) {
                            list = (List<String>) resultObj;
                        } else {
                            list = new ArrayList<>();
                            resultMap.put(key, list);
                        }
                        list.add((String) propValue);
                    }
                    it.remove();
                } else {
                    String currentKey = key.substring(0, key.indexOf("."));
                    Map<String, Object> childMap = getChildMap(propMap, currentKey);
                    Map<String, Object> map = parseToMap(childMap);
                    resultMap.put(currentKey, map);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 获取拥有相同父级节点的子节点
     *
     * @param propMap
     * @param currentKey
     * @return
     */
    private static Map<String, Object> getChildMap(Map<String, Object> propMap, String currentKey) {
        Map<String, Object> childMap = new Hashtable<>();
        try {
            Iterator<Map.Entry<String, Object>> iterator = propMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                String key = entry.getKey();
                if (key.contains(currentKey + ".")) {
                    key = key.substring(key.indexOf(".") + 1);
                    childMap.put(key, entry.getValue());
//                    iterator.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return childMap;
    }

    /**
     * map集合转化为yaml格式字符串
     *
     * @param propMap
     * @return
     */
    public static StringBuffer map2YamlString(Map<String, Object> propMap) {
        //默认deep 为零,表示不空格,deep 每加一层,缩进两个空格
        return map2YamlString(propMap, 0);
    }

    /**
     * 把Map集合转化为yaml格式 String字符串
     *
     * @param propMap map格式配置文件
     * @param deep    树的层级,默认deep 为零,表示不空格,deep 每加一层,缩进两个空格
     * @return
     */
    private static StringBuffer map2YamlString(Map<String, Object> propMap, int deep) {
        StringBuffer yamlBuffer = new StringBuffer();
        try {
            if (CollectionUtils.isEmpty(propMap)) {
                return yamlBuffer;
            }
            String space = getSpace(deep);
            for (Map.Entry<String, Object> entry : propMap.entrySet()) {
                String key = entry.getKey();
                Object valObj = entry.getValue();
                if (key.contains("[") && key.contains("]")) { //list下是一个对象
                    Map<String, Object> valMap = (Map<String, Object>) valObj;
                    if (CollectionUtils.isEmpty(valMap)) {
                        return yamlBuffer;
                    }
                    key = key.substring(0, key.indexOf("[")) + ":";
                    yamlBuffer.append(space + key + "\n");
                    yamlBuffer.append(getSpace(deep + 1) + "- ");
                    //在map集合中任意取一个key作为'-'后追加的key
                    String removeKey = "";
                    for (Map.Entry<String, Object> valEntry : valMap.entrySet()) {
                        removeKey = valEntry.getKey();
                        Map<String, Object> val = (Map<String, Object>) valEntry.getValue();
                        yamlBuffer.append(removeKey + ":\n");
                        StringBuffer valStr = map2YamlString(val, deep + 3);
                        yamlBuffer.append(valStr.toString());
                        break;
                    }
                    //移除已使用过的
                    valMap.remove(removeKey);
                    StringBuffer valStr = map2YamlString(valMap, deep + 2);
                    yamlBuffer.append(valStr.toString());
                } else {
                    key = space + key + ":";
                    if (valObj instanceof String) { //值为value 类型,不用再继续遍历
                        yamlBuffer.append(key + " " + (String) valObj + "\n");
                    } else if (valObj instanceof List) { //yaml List 集合格式
                        yamlBuffer.append(key + "\n");
                        List<String> list = (List<String>) entry.getValue();
                        String lSpace = getSpace(deep + 1);
                        for (String str : list) {
                            yamlBuffer.append(lSpace + "- " + str + "\n");
                        }
                    } else if (valObj instanceof Map) { //继续递归遍历
                        Map<String, Object> valMap = (Map<String, Object>) valObj;
                        yamlBuffer.append(key + "\n");
                        StringBuffer valStr = map2YamlString(valMap, deep + 1);
                        yamlBuffer.append(valStr.toString());
                    } else {
                        yamlBuffer.append(key + " " + valObj + "\n");
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return yamlBuffer;
    }

    /**
     * 获取缩进空格
     *
     * @param deep
     * @return
     */
    private static String getSpace(int deep) {
        StringBuffer buffer = new StringBuffer();
        if (deep == 0) {
            return "";
        }
        for (int i = 0; i < deep; i++) {
            buffer.append("  ");
        }
        return buffer.toString();
    }

    /**
     * properties 格式转化为 yaml 格式字符串
     *
     * @param properties
     * @return
     */
    public static StringBuffer prop2YmlString(Properties properties) {
        if (properties == null || properties.isEmpty()) {
            return new StringBuffer();
        }
        Map<String, Object> map = prop2Map(properties);
        StringBuffer stringBuffer = map2YamlString(map);
        return stringBuffer;
    }

}
package com.liftsail.testprofiledemo.utiltest;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.FileSystemResource;

import java.io.*;
import java.util.Properties;

/**
 * @Author: liftsail
 * @Date: 2022/12/2 10:14
 * @Description: 不积跬步无以至千里
 * 配置文件操作工具类
 */
public class PropertiesUtil {

    private static final String ENCODING = "utf-8";

    /**
     * 加载获取yaml配置文件
     *
     * @param filePath
     * @return
     */
    public static Properties loadYaml(String filePath) {
        Properties properties = null;
        try {
            YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            yaml.setResources(new FileSystemResource(filePath));
            properties = yaml.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return properties;
    }

    /**
     * 加载获取properties配置文件
     *
     * @param filePath
     * @return
     */
    public static Properties loadProperties(String filePath) {
        FileInputStream fis = null;
        Properties properties = new Properties();
        try {
            //fis = new FileInputStream(new File(filePath, ENCODING));
            fis = new FileInputStream(new File(filePath));
            properties.load(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return properties;
    }

    /**
     * 把properties配置文件写到指定位置
     *
     * @param filePath
     * @param properties
     */
    public static void write2Properties(Properties properties, String filePath) {
        FileOutputStream fos = null;
        try {
            if (properties == null) {
                return;
            }
            fos = new FileOutputStream(new File(filePath));
            properties.store(fos, "hello");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 把 properties 转化为yaml 格式,输出到指定位置
     *
     * @param properties
     * @param filePath
     */
    public static void write2Yaml(Properties properties, String filePath) {
        try {
            if (properties == null) {
                return;
            }
            //properties 转化为yaml 格式字符串
            StringBuffer ymlString = PropertiesToMapUtil.prop2YmlString(properties);
            writeStr2File(ymlString, filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 把字符串写到指定的文件
     *
     * @param msg
     * @param filePath
     */
    public static void writeStr2File(StringBuffer msg, String filePath) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(filePath));
            //将字符串写到指定文件
            fos.write(msg.toString().getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}

 

public static void main(String[] args) {
        Properties properties = loadProperties("D:\\application.properties");
        write2Yaml(properties, "D:\\application.yaml");
}

 

标签:Map,return,String,yml,application,key,new,properties
From: https://www.cnblogs.com/liftsail/p/16944148.html

相关文章