闽公网安备 35020302035485号
因为springBoot 的配置文件如果用properties会有中文乱码的问题,但是如果改成yml就不会有乱码问题,所以便有了把properties配置文件转化为yml配置文件的需求。
properties配置文件转化为yml代码如下:
import com.xiaoleilu.hutool.io.FileUtil;
import org.junit.jupiter.api.Test;
import org.springframework.util.StringUtils;
import java.util.*;
/**
* 堆代码 duidaima.com
*/
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";
}
}
总结:
以上便是properties配置文件如何转成yml文件的转换代码,有需要转换格式的同学可以参考一下。