直接贴代码吧
public class TqPath2CatalogUtils {
public static class Catalog {
private String name;
@JsonIgnore
private int level;
private List<Catalog> children;
public Catalog(String name) {
this.name = name;
children = new LinkedList<>();
}
public Catalog(String name,int level) {
this.name = name;
this.level = level;
children = new LinkedList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addChild(String name) {
for (Catalog catalog: children) {
if (name.equals(catalog.name)){
return ;
}
}
children.add(new Catalog(name));
}
public void addChild(String name,int level) {
for (Catalog catalog: children) {
if (name.equals(catalog.name) && level == catalog.getLevel()){
return ;
}
}
children.add(new Catalog(name,level));
}
public List<Catalog> getChildren() {
return children;
}
public void setChildren(List<Catalog> children) {
this.children = children;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
/**1、第一步,先把所有的路径单独拆出来构建目录树*/
public static List<Catalog> array2Catalogs(String[] paths,String separator){
List<Catalog> catalogs = new LinkedList<>();
for (String path : paths) {
String[] s = path.split(separator);
if (s.length > 0){
for (int i = 0; i < s.length; i++) {
String name = s[i];
Catalog curCatalog = null;
boolean isExist = false;
for (Catalog catalog : catalogs) {
if (catalog.getName().equals(name) && i==catalog.getLevel()){
curCatalog = catalog;
isExist = true;
}
}
if (!isExist){
curCatalog = new Catalog(name,i);
}
if (i!=s.length-1){
curCatalog.addChild(s[i+1],i+1);
}
if (!isExist){
catalogs.add(curCatalog);
}
}
}
}
return catalogs;
}
/**2、第二步,基于单独构建的目录树,构建一个统一的树根,那就是链表中的第一个元素*/
public static void buildCatalogTree(List<Catalog> catalogs, Catalog catalog){
if (catalogs==null || catalogs.size()==0 ||
catalog.getChildren() == null || catalog.getChildren().size()==0){
return;
}
List<Catalog> childs = catalog.getChildren();
List<Catalog> newChilds = new ArrayList<>();
int len = catalogs.size();
for (int i = 1; i < len; i++) {
Catalog cat = catalogs.get(i);
String catName = cat.getName();
int level = cat.getLevel();
for (Catalog child : childs) {
String name = child.getName();
if (catName.equals(name) && level == child.getLevel()){
newChilds.add(cat);
}
}
}
if (newChilds.size()>0){
catalog.setChildren(newChilds);
}
for (Catalog newChild : newChilds) {
buildCatalogTree(catalogs,newChild);
}
}
}