开发中遇到这样的需求:
记录一下获取war包中的数据, 提供的是war包下文件的路径字符串,需要将这些字符串解析成war包本身的层级结构显示
package tree;
import lombok.Data;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@Data
public class EntriesTreeNode {
private String name;
private String path;
private Boolean dir;
private Set<EntriesTreeNode> _children = new LinkedHashSet<>();
public Set<EntriesTreeNode> get_children() {
return _children;
}
public void set_children(Set<EntriesTreeNode> _children) {
this._children = _children;
}
@Override
public String toString() {
return "EntriesTreeNode{" +
"name='" + name + '\'' +
", path='" + path + '\'' +
", dir=" + dir +
", _children=" + _children +
'}';
}
public EntriesTreeNode(String name, String path, Boolean dir){
this.name = name;
this.path = path;
this.dir = dir;
}
public EntriesTreeNode addChildren(String dataName,String path){
for (EntriesTreeNode child : _children) {
if(dataName.equals(child.name)){
if(child._children.size() > 0){
// 是文件夹
child.dir = true;
}
return child;
}
}
return addChildren(new EntriesTreeNode(dataName,path,false));
}
public EntriesTreeNode addChildren(EntriesTreeNode children){
_children.add(children);
this.dir = true;
return children;
}
public static List<EntriesTreeNode> getTreeFromList(List<String> pathList){
EntriesTreeNode headNode = new EntriesTreeNode("/", "name" + "/", true);
EntriesTreeNode curent = headNode;
for (String path : pathList) {
EntriesTreeNode root = curent;
String[] split = path.split("/");
for (int i = 0; i < split.length; i++) {
StringBuilder tempPath = new StringBuilder();
for (int j = 0; j <= i; j++) {
tempPath.append("/").append(split[j]);
}
curent = curent.addChildren(split[i],tempPath.toString());
}
curent = root;
}
return new ArrayList<EntriesTreeNode>(headNode.get_children());
}
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
String s1 = "a/b/v/d";
String s2 = "a/c/d/f";
String s3 = "e/g/j";
stringList.add(s1);
stringList.add(s2);
stringList.add(s3);
List<EntriesTreeNode> fromList = EntriesTreeNode.getTreeFromList(stringList);
fromList.forEach(list-> System.out.println(list));
}
}
结果:
EntriesTreeNode{name='a', path='/a', dir=true, _children=[EntriesTreeNode{name='b', path='/a/b', dir=true, _children=[EntriesTreeNode{name='v', path='/a/b/v', dir=true, _children=[EntriesTreeNode{name='d', path='/a/b/v/d', dir=false, _children=[]}]}]}, EntriesTreeNode{name='c', path='/a/c', dir=true, _children=[EntriesTreeNode{name='d', path='/a/c/d', dir=true, _children=[EntriesTreeNode{name='f', path='/a/c/d/f', dir=false, _children=[]}]}]}]}
EntriesTreeNode{name='e', path='/e', dir=true, _children=[EntriesTreeNode{name='g', path='/e/g', dir=true, _children=[EntriesTreeNode{name='j', path='/e/g/j', dir=false, _children=[]}]}]}