树形文件读取和导出

package com.liuyang.service;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

public class test {
    public static void main(String[] args) {
        // step 1: read the file
        try (BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\86150\\Desktop\\test\\exam-data-2022.txt"))) {
            String line;
            /* each line of the file will be converted into an object and stored in a list */
            List<UserExampleExam> userExampleExams = new ArrayList<>();

            // step 2: read each line of the file
            while ((line = br.readLine()) != null) {
                // step 3: separate each line with a comma to form a new array
                String[] data = line.split(",");
                // step 4: encapsulate the array as an object
                UserExampleExam userExampleExam = DataStitching(data.length, data);
                // add the object to the list
                userExampleExams.add(userExampleExam);
            }

            // step 5: list parent-child relationships based on id and managerId
            List<UserExampleExam> newUserExampleExams = LoopOutput(userExampleExams);

            // step 6: format the result style and write to the result file
            output(newUserExampleExams);

        } catch (IOException e) {
            System.err.println("Failed to read file: " + e.getMessage());
        }
    }

    /**
     * file output
     * @param
     */
    private static void output(List<UserExampleExam> data) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\86150\\Desktop\\test\\file.txt"))) {

            List<List<String>> lists = FormatConversion(data);

            // 将 List<List<String>> 转换成 List<String>
            List<String> UserExampleExamList = lists.stream().flatMap(List::stream).collect(Collectors.toList());

            Iterator<String> iter = UserExampleExamList.iterator();

            while (iter.hasNext()) {
                bw.write(iter.next());
            }
        } catch (IOException e) {
            System.err.println("Failed to write file: " + e.getMessage());
        }
    }

    /**
     * Objects are broken down into lists
     * @param data
     */
    private static List<List<String>> FormatConversion(List<UserExampleExam> data) {

        ArrayList<List<String>> UserExampleExamString = new ArrayList<>();
        for (UserExampleExam datum : data) {
            UserExampleExamString.add(treeToList(datum));
        }
        return UserExampleExamString;
    }


    /**
     * Entities become data
     * @param node
     * @return
     */
    public static List<String> treeToList(UserExampleExam node) {
        List<String> result = new ArrayList<>();
        // 将当前节点对象转换为字符串,并添加到结果列表中
//        result.add(node.toString());
        // TODO: 2023/6/26  格式转化
        result.add(node.toMyString());
        result.add("\n");
        // 递归遍历当前节点的子节点,并将所有的子节点对象转换为字符串添加到结果列表中
        for (UserExampleExam child : node.children) {
            List<String> childResult = treeToList(child);
            result.addAll(childResult);
        }
        return result;
    }

    /**
     * The loop outputs parent-child level relationships
     * @param userExampleExams
     */
    private static List<UserExampleExam> LoopOutput(List<UserExampleExam> userExampleExams) {
        //2、组装成父子的树形结构
        //2.1)、找到所有的一级分类,给children设置子分类
        return userExampleExams.stream()
                // 过滤找出一级分类
                .filter(categoryEntity -> categoryEntity.getManagerId() == "null")
                // 处理,给一级菜单递归设置子菜单
                .peek(menu -> {
                    menu.setFlag(0);
                    menu.setChildren(getChildless(menu, userExampleExams));
                } )
                // 按sort属性排序
                .collect(Collectors.toList());
    }
    private static List<UserExampleExam> getChildless(UserExampleExam menu, List<UserExampleExam> userExampleExams) {

        return userExampleExams.stream()
                .filter(categoryEntity -> categoryEntity.getManagerId().equals(menu.getId()))
                .peek(categoryEntity -> {
                    // 找到子菜单
                    int flag = menu.getFlag();
                    categoryEntity.setFlag(++flag);
                    categoryEntity.setChildren(getChildless(categoryEntity, userExampleExams));
                })
                .collect(Collectors.toList());
    }

    /**
     * Encapsulates the object
     * @param length
     * @param data
     * @return
     */
    private static UserExampleExam DataStitching(int length, String[] data) {
        UserExampleExam userExampleExam = new UserExampleExam();
        userExampleExam.setName(data[0]);
        userExampleExam.setId(data[1]);
        userExampleExam.setAge(data[2]);
        if (length==3) {
            userExampleExam.setManagerId("null");
        } else {
            userExampleExam.setManagerId(data[3]);
        }
        return userExampleExam;
    }


    /**
     * Entity: UserExampleExam
     */
    private static class UserExampleExam {

        String name;

        String id;

        String age;

        String managerId;

        int flag = 0; // 级别(最高级别为0,依次累加)

        public UserExampleExam() {
        }

        public UserExampleExam(String name, String id, String age, String managerId) {
            this.name = name;
            this.id = id;
            this.age = age;
            this.managerId = managerId;
        }

        public UserExampleExam(String name, String id, String age, String managerId, int flag, List<UserExampleExam> children) {
            this.name = name;
            this.id = id;
            this.age = age;
            this.managerId = managerId;
            this.flag = flag;
            this.children = children;
        }

        public int getFlag() {
            return flag;
        }

        public void setFlag(int flag) {
            this.flag = flag;
        }

        public List<UserExampleExam> getChildren() {
            return children;
        }

        public void setChildren(List<UserExampleExam> children) {
            this.children = children;
        }

        private List<UserExampleExam> children;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

        public String getManagerId() {
            return managerId;
        }

        public void setManagerId(String managerId) {
            this.managerId = managerId;
        }

        /**
         * The original toString method
         * @return
         */
        @Override
        public String toString() {
            return "UserExampleExam{" +
                    "name='" + name + '\'' +
                    ", id='" + id + '\'' +
                    ", age='" + age + '\'' +
                    ", managerId='" + managerId + '\'' +
                    ", flag=" + flag +
                    ", children=" + children +
                    '}';
        }

        /**
         * Personalized toString method
         * @return
         */
        public String toMyString() {
            String line = "--";
            for (int i = 1; i <= flag; i++) {
                line = line + "----";
            }
            if(managerId == "null"){
                return line + " " + name + ", " + id + ", " + age;
            } else{
                return line + " " + name + ", " + id + ", " + age + ", " + managerId;
            }
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值