properties与yaml互转工具类

news/2024/7/7 13:40:00

没事写的,实际更加推荐使用网上一些更加完善的在线工具
效果
正向转换
原内容

转换结果
在这里插入图片描述
反向
原内容
在这里插入图片描述
结果
在这里插入图片描述
主要类

public class p2y {

    private static final String REVERSE = "-r";
    private static final Pattern PATTERN = Pattern.compile("(.+)\\[(\\d+)]$");

    public static void main(String[] args) throws IOException {
        args = new String[]{"src/p2y/test.yaml","-r"};
        if (args.length == 1) {
            handleP2y(args[0]);
        } else if (args.length == 2) {
            if (args[1].equals(REVERSE)) {
                handleY2p(args[0]);
            } else {
                printHelp();
            }
        } else {
            printHelp();
        }
    }

    private static void handleY2p(String path) throws IOException {
        List<String> lines = Files.readAllLines(Paths.get(path), Charset.forName("UTF-8"));
        LinkedList<State> stack = new LinkedList<>();
        for (String line : lines) {
            handleLine(stack, line);
        }
    }

    private static void handleLine(LinkedList<State> stack, String line) {
        int index;
        String name;
        String value;
        for (int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);
            switch (c) {
                case ' ':
                case '\t':
                    break;
                case '#':
                    System.out.println(line);
                    return;
                case '-':
                    stack.peekLast().index++;
                    index = line.indexOf(':');
                    if(index!=-1){
                        name=line.substring(i+2,index).trim();
                        while (!stack.isEmpty()&&stack.peekLast().num>=i+2){
                            stack.pollLast();
                        }
                        stack.addLast(new State(name,i+2));
                    }else {
                        value=line.substring(i+2).trim();
                        printLine(stack,null,value);
                    }
                    return;
                default:
                    index = line.indexOf(':');
                    name=line.substring(i,index);
                    value=line.substring(index+1);
                    while (!stack.isEmpty()&&stack.peekLast().num>=i){
                        stack.pollLast();
                    }
                    if(value.trim().length()>0){
                        printLine(stack,name,value);
                    }else {
                        stack.addLast(new State(name,i));
                    }
                    return;
            }
        }
    }

    private static void printLine(LinkedList<State> stack, String name, String value) {
        StringBuilder builder=new StringBuilder();
        for (State state:stack){
            builder.append(state.getValue()).append('.');
        }
        if(name!=null){
            builder.append(name);
        }else {
            builder.setLength(builder.length()-1);
        }
        builder.append('=').append(value.trim());
        System.out.println(builder);
    }

    static class State {

        private String name;
        private int num;
        private int index;

        public State(String name, int num) {
            this.name = name;
            this.num = num;
            index=-1;
        }

        public String getValue() {
            if(index!=-1){
                return name+"["+index+"]";
            }else {
                return name;
            }
        }

    }

    private static void handleP2y(String path) throws IOException {
        List<String> lines = Files.readAllLines(Paths.get(path), Charset.forName("UTF-8"));
        Node root = new Node();
        for (String line : lines) {
            handleLine(root, line);
        }
        for (Map.Entry<String, Node> entry : root.map.entrySet()) {
            printYaml(entry.getKey(), entry.getValue(), 0);
        }
    }

    private static void printYaml(String name, Node node, int num) {
        if (node.value != null) {//普通值
            if (name != null) {
                print(num, name + ": " + node.value);
            } else {
                print(num, "- " + node.value);
            }
        } else if (node.map != null) {// map
            if (name != null) {
                print(num, name + ":");
                for (Map.Entry<String, Node> entry : node.map.entrySet()) {
                    printYaml(entry.getKey(), entry.getValue(), num + 2);
                }
            } else {
                // 注意第一次
                boolean first = true;
                for (Map.Entry<String, Node> entry : node.map.entrySet()) {
                    if (first) {
                        first = false;
                        printYaml("- " + entry.getKey(), entry.getValue(), num);
                    } else {
                        printYaml(entry.getKey(), entry.getValue(), num + 2);
                    }
                }
            }
        } else {//数组情况
            print(num, name + ":");
            for (Node chid : node.list) {
                printYaml(null, chid, num + 2);
            }
        }
    }

    private static void print(int num, String msg) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < num; i++) {
            builder.append(' ');
        }
        builder.append(msg);
        System.out.println(builder);
    }

    private static void handleLine(Node root, String line) {
        int index = line.indexOf('=');
        if (index == -1) return;
        String[] names = line.substring(0, index).split("\\.");
        next(root, names, 0, line.substring(index + 1));
    }

    private static void next(Node node, String[] names, int index, String value) {
        if (index < names.length) {
            next(node.getOrAdd(names[index]), names, index + 1, value);
        } else {
            node.value = value;
        }
    }

    static class Node {

        private Map<String, Node> map;
        private List<Node> list;
        private String value;

        public Node getOrAdd(String name) {
            Matcher matcher = PATTERN.matcher(name);
            if (matcher.find()) {
                Node node = handleMap(matcher.group(1));
                return node.handleList(Integer.parseInt(matcher.group(2)));
            } else {
                return handleMap(name);
            }
        }

        private Node handleList(int index) {
            if (list == null) list = new ArrayList<>();
            while (list.size() <= index) {
                list.add(new Node());
            }
            return list.get(index);
        }

        private Node handleMap(String name) {
            if (map == null) map = new HashMap<>();
            if (!map.containsKey(name)) {
                map.put(name, new Node());
            }
            return map.get(name);
        }

        @Override
        public String toString() {
            return "Node{" +
                    "map=" + map +
                    ", list=" + list +
                    ", value='" + value + '\'' +
                    '}';
        }

    }

    private static final String HELP = "功能:用于prop与yaml文件互转\n参数错误!\n需要先指明文件路径\n可以使用" + REVERSE +
            "指定y->p,默认是p->y\n可以使用>重定向到指定文件,默认输出到屏幕";

    private static void printHelp() {
        System.err.println(HELP);
    }

}

原类默认是为了写成,控制台程序的方便使用 使用控制台参数


http://www.niftyadmin.cn/n/658007.html

相关文章

IDEA default keymap整理

main menu ctrlalts 打开settings ctrlaltshifts 打开project Structure alt1 打开项目目录 alt7 打开Structure目录 altf12 代开teminal git ctrlaltz revert ctrlk commit project ctrlshiftk push edit ctrly删除行 ctrldelete删除到单词末尾 ctrlbackspace删除到单词首 ctr…

马化腾在小程序首次获选世界互联网领先科技成果奖发表演讲

昨日小程序斩获一项世界级殊荣——在乌镇举行的第五届世界互联网大会“世界互联网领先科技成果发布活动”上&#xff0c;作为一项全新的技术和应用创新&#xff0c;小程序首次获选世界互联网领先科技成果。腾讯公司董事会主席兼首席执行官马化腾作为腾讯公司代表上台领奖&#…

Java小图片拼接为图集

使用的是暴力拼接(从左向右&#xff0c;从上到下&#xff0c;先放矮的图片进去) 对于后缀为_strip[数字]的图片会再次分割提高图集密度 效果 拼接前 拼接后 对应子图的偏移信息记录类(自动生成) 单张图片信息类(可能有多张图片因为有后面名为_strip[数字]的情况) public cl…

以xml文件作为数据库的程序一例

xml分为三种&#xff0c;index.xml保存一个最大的索引 &#xff0c;相当于一个序列。flfgcx_list.xml为一个目录&#xff0c;里面保存了所有的信息的索引信息另一种就是内容xml&#xff0c;每一种法律都有一个文件。文件名为一个数字&#xff0c;当录入当前的法律的时候自动创造…

三汇自动挂断问题

三汇自动挂断问题 ACK检测 转载于:https://www.cnblogs.com/devour/p/10901341.html

Java正则表达式使用

这里不讲基本的正则字符&#xff0c;只说一下Java中使用正则的常用API 基本代码&#xff0c;后面的基于他们 // 构建正则 Pattern pattern Pattern.compile("((\\d)(\\d))"); // 匹配字符串 Matcher matcher pattern.matcher("23sgfew8h8erh23gewjrg3er&quo…

推荐两个不错的flink项目

最近flink真是风生水起&#xff0c;但是浪院长看来这不过是阿里错过了创造spark影响力之后&#xff0c;想要在flink领域创建绝对的影响力。但是&#xff0c;不可否认flink在实时领域确实目前来看独树一帜&#xff0c;当然也有它不适合的地方&#xff0c;比如今天要推荐的第一个…

LOJ 6433 「PKUSC2018」最大前缀和——状压DP

题目&#xff1a;https://loj.ac/problem/6433 想到一个方案中没有被选的后缀满足 “该后缀的任一前缀和 <0 ”。 于是令 dp[ S ] 表示选了点集 S &#xff0c;满足任一前缀和 <0 的方案。很好转移。 令 f[ S ] 表示选了点集 S &#xff0c;且 S 整体就是最大前缀和的方案…