我也添加了一个父指针。也许不用它也可以解析文本,但是父指针使它更容易。首先,您需要具有更多的构造函数:
static final int root_depth = 4; // assuming 4 whitespaces precede the tree rootpublic Section(String text, int depth) { this.text = text; this.depth = depth; this.children = new ArrayList<Section>(); this.parent = null;}public Section(String text, int depth, Section parent) { this.text = text; this.depth = depth; this.children = new ArrayList<Section>(); this.parent = parent;}然后,当您开始解析文件时,请逐行读取它:
Section prev = null;for (String line; (line = bufferedReader.readLine()) != null; ) { if (prev == null && line begins with root_depth whitespaces) { Section root = new Section(text_of_line, root_depth); prev = root; } else { int t_depth = no. of whitespaces at the beginning of this line; if (t_depth > prev.getDepth()) // assuming that empty sections are not allowed Section t_section = new Section(text_of_line, t_depth, prev); prev.addChild(t_section); } else if (t_depth == prev.getDepth) { Section t_section = new Section(text_of_line, t_depth, prev.getParent()); prev.getParent().addChild(t_section); } else { while (t_depth < prev.getDepth()) { prev = prev.getParent(); } // at this point, (t_depth == prev.getDepth()) = true Section t_section = new Section(text_of_line, t_depth, prev.getParent()); prev.getParent().addChild(t_section); } }}我已经掩盖了伪代码的一些细节,但我认为您已经获得了如何进行此解析的总体思路。请记住要实现addChild(),getDepth(),getParent()等方法。



