/**
* 本地yaml文件转换为properties格式
* @param filePath 文件路径+文件名
* */
public static List<String> yamlToPropertiesString(String filePath){
List<String> resultList = new ArrayList<>();
//获取本地yaml文件,转换为字符串
String resultStr = reedLineForFile(filePath);
if (resultStr != null){
Yaml yaml = new Yaml();
//转换为properties格式
Object object = yaml.load(resultStr);
resultList = travelRootWithResult(object);
}
return resultList;
}
/**
* 读取本地文件
* 一次读取一行
* */
public static String reedLineForFile(String filePath){
File readFile = new File(filePath);
BufferedReader reader = null;
String resultStr = null;
try{
reader = new BufferedReader(new FileReader(readFile));
String tempString = null;
StringBuffer sbf = new StringBuffer();
while ((tempString = reader.readLine()) != null){//BufferedReader有readLine(),可以实现按行读取
sbf.append(tempString).append("\n");
}
reader.close();
resultStr = sbf.toString();
}catch(IOException e){
e.printStackTrace();
}finally{
if(reader != null){
try{
reader.close();
}catch(IOException e){
}
}
return resultStr;
}
}
/**
* yaml转换为properties格式
* 获取key
* */
private static List<String> travelRootWithResult(Object object) {
List<String> resultList = new ArrayList<>();
if (object instanceof LinkedHashMap) {
LinkedHashMap map = (LinkedHashMap) object;
Set<Object> keySet = map.keySet();
for (Object key : keySet) {
List<String> keyList = new ArrayList<>();
keyList.add((String) key);
travelTreeNode(map.get(key), keyList, resultList);
}
}
return resultList;
}
/**
* yaml转换为properties格式
* 拼接成properties字符串
* */
private static void travelTreeNode(Object obj, List<String> keyList, List<String> resultList) {
if (obj instanceof LinkedHashMap) {
LinkedHashMap linkedHashMap = (LinkedHashMap) obj;
linkedHashMap.forEach((key, value) -> {
if (value instanceof LinkedHashMap) {
keyList.add((String) key);
travelTreeNode(value, keyList, resultList);
keyList.remove(keyList.size() - 1);
} else {
StringBuilder result = new StringBuilder();
for (String strKey : keyList) {
result.append(strKey).append(".");
}
result.append(key).append("=").append(value);
System.out.println(result);
resultList.add(result.toString());
}
});
} else {
StringBuilder result = new StringBuilder();
result.append(keyList.get(0)).append("=").append(obj);
System.out.println(result);
resultList.add(result.toString());
}
}
yaml文件格式转properties格式
最新推荐文章于 2024-05-28 18:00:00 发布