java yaml转properties工具类方式

yaml转properties工具类

yaml文件转properties文件

yaml字符串转properties字符串

yaml转Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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 配置文件转 Properties 配置文件工具类
 */
public class YmlUtils {
 
    private static final String lineSeparator = "n";
 
    /**
     * 将 yml 字符串化为 properties字符串
     *
     * @param yml
     * @return
     */
    public static String yamlStr2PropStr(String yml) {
        List nodeList = getNodeList(yml);
        // 去掉多余数据,并打印
        String str = printNodeList(nodeList);
        return str;
    }
 
    /**
     * 将 yml 文件转化为 properties 文件
     *
     * @param ymlFileName 工程根目录下(非resources目录)的 yml 文件名称(如:abc.yml)
     * @return List 每个Nyml 文件中每行对应解析的数据
     */
    public static List 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 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;
    }
 
    /**
     * 将yml转化为porperties文件,并获取转化后的Map键值对
     *
     * @param ymlFileName 工程根目录下的 yml 文件名称
     * @return 转化后的 porperties 文件键值对Map
     */
    public static Map yamlFile2Map(String ymlFileName) {
        Map map = new HashMap();
        List 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 yamlStr2Map(String yaml) {
        Map map = new HashMap();
        List 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 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 getNodeList(String yml) {
        String[] lines = yml.split(lineSeparator);
        List nodeList = new ArrayList();
        Map keyMap = new HashMap();
        Set 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 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 cloud的maven进行构造的项目,在把properties换成yml后,一定要进行mvn clean insatll

application.properties中:

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

yml中:

1
2
3
4
5
6
7
8
9
server:
    port: 8801
 
eureka:
   client:
     registerWithEureka: false
     fetchRegistry: false
     serviceUrl:
      defaultZone: http://localhost:8801/eureka/

以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/6868.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部