properties转换yml格式

java

浏览数:446

2019-1-13

AD:资源代下载服务


springBoot 的配置文件如果用properties会有中文乱码的问题,改成yml可以解决。该工具应运而生。

import com.xiaoleilu.hutool.io.FileUtil;
import org.junit.jupiter.api.Test;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by DimonHo on 2017/11/3.
 */
public class AnalyzerFiler {
    /**
     * properties转yml
     * @param propertiesPath
     * @param propertiesCharset
     * @param ymlCharset
     * @return
     */
    public String propertiesToYml(String propertiesPath,String propertiesCharset,String ymlCharset){
        List<String> lines = FileUtil.readLines(propertiesPath, propertiesCharset);
        String path = FileUtil.getAbsolutePath(propertiesPath);
        //使用treemap排好序
        Map<String,String> sourceMap = new TreeMap<String,String>();
        for (String line:lines){
            if (!StringUtils.isEmpty(line) && !line.startsWith("#")){
                String key = line.substring(0,line.indexOf("="));
                String value = line.substring(line.indexOf("=")+1);
                sourceMap.put(key,value);
            }
        }
        Iterator<String> it = sourceMap.keySet().iterator();
        //保存yml的行内容
        List<String> ymlLines = new ArrayList<String>();
        //Tab用两个空格格式化
        String tab = "  ";

        //yml文档树
        Map<String,List<String>> treeMap = new TreeMap<String,List<String>>();
        //父级名称
        String parent = "";
        //子节点列表
        List<String> element = new ArrayList<String>();

        while(it.hasNext()){
            String key = it.next();
            //.拆分key
            String[] keys = key.split("\\.");
            String prefix = "";
            for (int i=0;i<keys.length;i++){
                //从第二个节点开始,行前面需要加tab来格式化,并设置它的父节点
                if (i>0){
                    parent+=keys[i-1];
                    prefix += tab;
                }
                String line = prefix + keys[i]+ ": ";
                if (treeMap.get(parent)==null) treeMap.put(parent,new ArrayList<String>());
                if(!treeMap.get(parent).contains(line)){
                    element = treeMap.get(parent)==null?new ArrayList<String>():treeMap.get(parent);
                    if (!element.contains(line)){
                        element.add(line);
                        treeMap.put(parent,element);
                    }
                    if (i==keys.length-1){
                        ymlLines.add(line+sourceMap.get(key));
                        parent = "";
                    }else{
                        ymlLines.add(line);
                    }
                }
            }
        }
        FileUtil.writeLines(ymlLines,path.replace(".properties",".yml"),ymlCharset);
        return "ok";
    }
}