iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >javayaml转properties工具类方式
  • 162
分享到

javayaml转properties工具类方式

java工具类yaml转propertiesjavayaml转properties 2022-11-13 18:11:00 162人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录yaml转properties工具类properties与yml之间的比较发现了几个要注意的地方yaml转properties工具类 yaml文件转properties文件 ya

yaml转properties工具类

yaml文件转properties文件

yaml字符串转properties字符串

yaml转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;


public class YmlUtils {

	private static final String lineSeparator = "\n";

	
	public static String yamlStr2PropStr(String yml) {
		List<Ymlnode> nodeList = getNodeList(yml);
		// 去掉多余数据,并打印
		String str = printNodeList(nodeList);
		return str;
	}

	
	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];
		// 获取文件数据
		String yml = read(ymlFile);
		List<YmlNode> nodeList = getNodeList(yml);
		// 去掉多余数据,并打印
		String str = printNodeList(nodeList);
		// 将数据写入到 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;
	}

	
	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);
		}
		// 标识是否最后一级
		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();
		// 初始化默认数据(防止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的,属于异常数据,不做处理
		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());
		// 获取当前层级
		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 {

	
	private Integer level;
	
	private String key;
	
	private String value;
	
	private Boolean emptyLine;
	
	private Boolean effective;
	
	private String headRemark;
	
	private String tailRemark;
	
	private Boolean last;
}

properties与yml之间的比较

在于其拥有天然的树状结构,所以着手尝试将properties文件更改为yml文件

发现了几个要注意的地方

1、在properties文件中是以”.”进行分割的, 在yml中是用”:”进行分割;

2、yml的数据格式和JSON的格式很像,都是K-V格式,并且通过”:”进行赋值;

3、在yml中缩进一定不能使用TAB,否则会报很奇怪的错误;(缩进特么只能用空格!!!!)

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

5、使用spring cloudMaven进行构造的项目,在把properties换成yml后,一定要进行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/

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: javayaml转properties工具类方式

本文链接: https://www.lsjlt.com/news/170230.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作