最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java yaml轉(zhuǎn)properties工具類方式

 更新時間:2022年10月27日 09:43:18   作者:阿拉的夢想  
這篇文章主要介紹了java yaml轉(zhuǎn)properties工具類方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

yaml轉(zhuǎn)properties工具類

yaml文件轉(zhuǎn)properties文件

yaml字符串轉(zhuǎn)properties字符串

yaml轉(zhuǎn)Map

package com.demo.utils;

import lombok.Data;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Stream;

/**
 * Yaml 配置文件轉(zhuǎn) Properties 配置文件工具類
 */
public class YmlUtils {

	private static final String lineSeparator = "\n";

	/**
	 * 將 yml 字符串化為 properties字符串
	 *
	 * @param yml
	 * @return
	 */
	public static String yamlStr2PropStr(String yml) {
		List<YmlNode> nodeList = getNodeList(yml);
		// 去掉多余數(shù)據(jù),并打印
		String str = printNodeList(nodeList);
		return str;
	}

	/**
	 * 將 yml 文件轉(zhuǎn)化為 properties 文件
	 *
	 * @param ymlFileName 工程根目錄下(非resources目錄)的 yml 文件名稱(如:abc.yml)
	 * @return List<Node> 每個Nyml 文件中每行對應(yīng)解析的數(shù)據(jù)
	 */
	public static List<YmlNode> yamlFile2PropFile(String ymlFileName) {
		if (ymlFileName == null || ymlFileName.isEmpty() || !ymlFileName.endsWith(".yml")) {
			throw new RuntimeException("請輸入yml文件名稱??!");
		}
		File ymlFile = new File(ymlFileName);
		if (!ymlFile.exists()) {
			throw new RuntimeException("工程根目錄下不存在 " + ymlFileName + "文件??!");
		}
		String fileName = ymlFileName.split(".yml", 2)[0];
		// 獲取文件數(shù)據(jù)
		String yml = read(ymlFile);
		List<YmlNode> nodeList = getNodeList(yml);
		// 去掉多余數(shù)據(jù),并打印
		String str = printNodeList(nodeList);
		// 將數(shù)據(jù)寫入到 properties 文件中
		String propertiesName = fileName + ".properties";
		File file = new File(propertiesName);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try (FileWriter writer = new FileWriter(file)) {
			writer.write(str);
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return nodeList;
	}

	/**
	 * 將yml轉(zhuǎn)化為porperties文件,并獲取轉(zhuǎn)化后的Map鍵值對
	 *
	 * @param ymlFileName 工程根目錄下的 yml 文件名稱
	 * @return 轉(zhuǎn)化后的 porperties 文件鍵值對Map
	 */
	public static Map<String, String> yamlFile2Map(String ymlFileName) {
		Map<String, String> map = new HashMap<>();
		List<YmlNode> list = yamlFile2PropFile(ymlFileName);
		String s = printNodeList(list);
		String[] lines = s.split(lineSeparator);
		Stream.of(lines).forEach(line -> {
			String[] split = line.split("=");
			map.put(split[0], split[1]);
		});
		return map;
	}

	public static Map<String, String> yamlStr2Map(String yaml) {
		Map<String, String> map = new HashMap<>();
		List<YmlNode> list = getNodeList(yaml);
		String s = printNodeList(list);
		String[] lines = s.split(lineSeparator);
		Stream.of(lines).forEach(line -> {
			String[] split = line.split("=");
			map.put(split[0], split[1]);
		});
		return map;
	}

	private static String read(File file) {
		if (Objects.isNull(file) || !file.exists()) {
			return "";
		}
		try (FileInputStream fis = new FileInputStream(file)) {
			byte[] b = new byte[(int) file.length()];
			fis.read(b);
			return new String(b, StandardCharsets.UTF_8);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	private static String printNodeList(List<YmlNode> nodeList) {
		StringBuilder sb = new StringBuilder();
		for (YmlNode node : nodeList) {
			if (node.getLast().equals(Boolean.FALSE)) {
				continue;
			}
			if (node.getEmptyLine().equals(Boolean.TRUE)) {
				sb.append(lineSeparator);
				continue;
			}
			// 判斷是否有行級注釋
			if (node.getHeadRemark().length() > 0) {
				String s = "# " + node.getHeadRemark();
				sb.append(s).append(lineSeparator);
				continue;
			}
			// 判斷是否有行末注釋 (properties中注釋不允許末尾注釋,故而放在上面)
			if (node.getTailRemark().length() > 0) {
				String s = "# " + node.getTailRemark();
				sb.append(s).append(lineSeparator);
			}
			//
			String kv = node.getKey() + "=" + node.getValue();
			sb.append(kv).append(lineSeparator);
		}
		return sb.toString();
	}

	private static List<YmlNode> getNodeList(String yml) {
		String[] lines = yml.split(lineSeparator);
		List<YmlNode> nodeList = new ArrayList<>();
		Map<Integer, String> keyMap = new HashMap<>();
		Set<String> keySet = new HashSet<>();
		for (String line : lines) {
			YmlNode node = getNode(line);
			if (node.getKey() != null && node.getKey().length() > 0) {
				int level = node.getLevel();
				if (level == 0) {
					keyMap.clear();
					keyMap.put(0, node.getKey());
				} else {
					int parentLevel = level - 1;
					String parentKey = keyMap.get(parentLevel);
					String currentKey = parentKey + "." + node.getKey();
					keyMap.put(level, currentKey);
					node.setKey(currentKey);
				}
			}
			keySet.add(node.getKey() + ".");
			nodeList.add(node);
		}
		// 標(biāo)識是否最后一級
		for (YmlNode each : nodeList) {
			each.setLast(getNodeLast(each.getKey(), keySet));
		}
		return nodeList;
	}

	private static boolean getNodeLast(String key, Set<String> keySet) {
		if (key.isEmpty()) {
			return true;
		}
		key = key + ".";
		int count = 0;
		for (String each : keySet) {
			if (each.startsWith(key)) {
				count++;
			}
		}
		return count == 1;
	}

	private static YmlNode getNode(String line) {
		YmlNode node = new YmlNode();
		// 初始化默認(rèn)數(shù)據(jù)(防止NPE)
		node.setEffective(Boolean.FALSE);
		node.setEmptyLine(Boolean.FALSE);
		node.setHeadRemark("");
		node.setKey("");
		node.setValue("");
		node.setTailRemark("");
		node.setLast(Boolean.FALSE);
		node.setLevel(0);
		// 空行,不處理
		String trimStr = line.trim();
		if (trimStr.isEmpty()) {
			node.setEmptyLine(Boolean.TRUE);
			return node;
		}
		// 行注釋,不處理
		if (trimStr.startsWith("#")) {
			node.setHeadRemark(trimStr.replaceFirst("#", "").trim());
			return node;
		}
		// 處理值
		String[] strs = line.split(":", 2);
		// 拆分后長度為0的,屬于異常數(shù)據(jù),不做處理
		if (strs.length == 0) {
			return node;
		}
		// 獲取鍵
		node.setKey(strs[0].trim());
		// 獲取值
		String value;
		if (strs.length == 2) {
			value = strs[1];
		} else {
			value = "";
		}
		// 獲取行末備注
		String tailRemark = "";
		if (value.contains(" #")) {
			String[] vs = value.split("#", 2);
			if (vs.length == 2) {
				value = vs[0];
				tailRemark = vs[1];
			}
		}
		node.setTailRemark(tailRemark.trim());
		node.setValue(value.trim());
		// 獲取當(dāng)前層級
		int level = getNodeLevel(line);
		node.setLevel(level);
		node.setEffective(Boolean.TRUE);
		return node;
	}

	private static int getNodeLevel(String line) {
		if (line.trim().isEmpty()) {
			return 0;
		}
		char[] chars = line.toCharArray();
		int count = 0;
		for (char c : chars) {
			if (c != ' ') {
				break;
			}
			count++;
		}
		return count / 2;
	}
}

@Data
class YmlNode {

	/**
	 * 層級關(guān)系
	 */
	private Integer level;
	/**
	 * 鍵
	 */
	private String key;
	/**
	 * 值
	 */
	private String value;
	/**
	 * 是否為空行
	 */
	private Boolean emptyLine;
	/**
	 * 當(dāng)前行是否為有效配置
	 */
	private Boolean effective;
	/**
	 * 頭部注釋(單行注釋)
	 */
	private String headRemark;
	/**
	 * 末尾注釋
	 */
	private String tailRemark;
	/**
	 * 是否為最后一層配置
	 */
	private Boolean last;
}

properties與yml之間的比較

在于其擁有天然的樹狀結(jié)構(gòu),所以著手嘗試將properties文件更改為yml文件

發(fā)現(xiàn)了幾個要注意的地方

1、在properties文件中是以”.”進(jìn)行分割的, 在yml中是用”:”進(jìn)行分割;

2、yml的數(shù)據(jù)格式和json的格式很像,都是K-V格式,并且通過”:”進(jìn)行賦值;

3、在yml中縮進(jìn)一定不能使用TAB,否則會報很奇怪的錯誤;(縮進(jìn)特么只能用空格?。。。。?/p>

4、每個k的冒號后面一定都要加一個空格;

5、使用spring cloud的maven進(jìn)行構(gòu)造的項目,在把properties換成yml后,一定要進(jìn)行mvn clean insatll

application.properties中:

server.port=8801
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http\://localhost\:${server.port}/eureka/

yml中:

server:
? ? port: 8801

eureka:
? ?client:
? ? ?registerWithEureka: false
? ? ?fetchRegistry: false
? ? ?serviceUrl:
? ? ? defaultZone: http://localhost:8801/eureka/

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Spring Boot + FreeMarker 實現(xiàn)動態(tài)Word文檔導(dǎo)出功能

    Spring Boot + FreeMarker 實現(xiàn)動態(tài)Word文檔導(dǎo)出功能

    Spring Boot與FreeMarker的組合,為開發(fā)者提供了一個強(qiáng)大的平臺,可以輕松實現(xiàn)動態(tài)Word文檔的導(dǎo)出,本文將指導(dǎo)你如何使用Spring Boot與FreeMarker模板引擎,創(chuàng)建一個簡單的應(yīng)用,用于根據(jù)數(shù)據(jù)庫數(shù)據(jù)動態(tài)生成Word文檔并下載,感興趣的朋友一起看看吧
    2024-06-06
  • 智能手表開發(fā)API接口

    智能手表開發(fā)API接口

    這篇文章主要介紹了智能手表開發(fā)API接口,使用圖靈機(jī)器人平臺接口實現(xiàn)天氣預(yù)報,非常簡單實用,這里推薦給大家。
    2015-03-03
  • IDEA在Maven項目中使用本地jar包的方法

    IDEA在Maven項目中使用本地jar包的方法

    我們在拿到舊項目的時候,經(jīng)常會遇到一種情況,就是這個項目的maven中依賴了一個本地的jar包,這種情況就需要引入這個jar包,所以本文給大家介紹了IDEA在Maven項目中使用本地jar包的方法,需要的朋友可以參考下
    2024-04-04
  • InvocationHandler中invoke()方法的調(diào)用問題分析

    InvocationHandler中invoke()方法的調(diào)用問題分析

    這篇文章主要介紹了InvocationHandler中invoke()方法的調(diào)用問題分析,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • springboot集成ES實現(xiàn)磁盤文件全文檢索的示例代碼

    springboot集成ES實現(xiàn)磁盤文件全文檢索的示例代碼

    這篇文章主要介紹了springboot集成ES實現(xiàn)磁盤文件全文檢索的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • 詳解Java中final的用法

    詳解Java中final的用法

    本文主要介紹了Java中final的使用方法,final是java的關(guān)鍵字,本文就詳細(xì)說明一下它的使用方法,需要的朋友可以參考下
    2015-08-08
  • Mybatis 簡介與原理

    Mybatis 簡介與原理

    MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優(yōu)秀的持久層框架。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設(shè)置參數(shù)以及獲取結(jié)果集
    2017-05-05
  • Java中的Semaphore信號量使用方法代碼實例

    Java中的Semaphore信號量使用方法代碼實例

    這篇文章主要介紹了Java中的Semaphore信號量使用方法代碼實例,Semaphore是一種基于計數(shù)的信號量,它可以設(shè)定一個閾值,基于此,多個線程競爭獲取許可信號,做自己的申請后歸還,超過閾值后,線程申請許可信號將會被阻塞,需要的朋友可以參考下
    2023-11-11
  • 詳解Spring Data Jpa當(dāng)屬性為Null也更新的完美解決方案

    詳解Spring Data Jpa當(dāng)屬性為Null也更新的完美解決方案

    這篇文章主要介紹了詳解Spring Data Jpa當(dāng)屬性為Null也更新的完美解決方案,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-02-02
  • Java throw Exception實現(xiàn)異常轉(zhuǎn)換

    Java throw Exception實現(xiàn)異常轉(zhuǎn)換

    這篇文章主要介紹了Java throw Exception實現(xiàn)異常轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04

最新評論

特克斯县| 抚顺县| 泰顺县| 台南市| 新邵县| 灵台县| 台北县| 嘉鱼县| 濮阳市| 巫山县| 桦川县| 襄垣县| 卢龙县| 哈尔滨市| 岑溪市| 建平县| 渝中区| 德清县| 武隆县| 滦南县| 兴文县| 澄江县| 海原县| 山东| 墨竹工卡县| 台中县| 墨竹工卡县| 石首市| 保德县| 浮山县| 易门县| 兴隆县| 神木县| 泸溪县| 扬州市| 垫江县| 元江| 延川县| 南充市| 长乐市| 敦化市|