目录路径列表中的节点层次结构

嗨我想建立一个基于目录结构的节点层次结构:

/first/ /first/second /first/third /first/third/forth /first/third/fifth /first/sixth /first/sixth/seventh /first/eighth /first/ninth 

我试图得到一个类似于此的节点层次结构:

 first second third forth fifth sixth seventh eighth ninth 

我为此使用Kotlin,对Java和Kotlin我还是比较新的,所以对我很感兴趣。

注意:我正在使用FileTreeWalk获取目录

 fun getDirs(directoryName: String): MutableList { val ret = mutableListOf() File(directoryName).walk().forEach { if (it.isDirectory) { ret.add(it.toString()) } } return ret } 

现在我所拥有的就是这样(生成一个扁平的层次结构):

 private fun nodesFromPathList(dirPaths: MutableList) : Tree.Node { val ret = Tree.Node("root") for (dir in dirPaths) { ret.add(Tree.Node(dir)) } return ret } 

有任何想法吗?

我决定把所有的节点放到一张地图上,并把这些节点连接起来。

  /** * Creates a node hierarchy from list of paths */ private fun nodesFromPathList(dirPaths: MutableList) : Tree.Node? { var ret : Tree.Node? = null val nodeMap = mutableMapOf() // Add a node for each directory path and put it into a map for (dir in dirPaths) { val newNode = Tree.Node(nodeName(dir), skin) if (ret == null) ret = newNode nodeMap.put(dir, newNode) } // Go through each one and add the child nodeMap.forEach { val parent = parentPath(it.key) try { nodeMap[parent]!!.add(it.value) } catch (e: NullPointerException) { println("Parent not found") } } return ret } /** * Returns current path * "D:\dir\to\apath" ==> "apath" */ fun nodeName(path: String): String { return path.split("\\").last() } /** * Returns the parent path * D:\dir\to\apath ==> D:\dir\to */ fun parentPath(path: String): String { val split = path.trim('\\').split("\\") var ret = "" for (i in 0..split.size-2) { ret += split[i] + "\\" } return ret.trim('\\') } 

我把路径放到键中,并把树节点放入值中。 迭代通过地图,并根据父母连接孩子。 示例图:

 [D:\android\assets=Tree$Node@56eb1af5, D:\android\assets\Assets\abc=Tree$Node@48e3456d, D:\android\assets\Assets\abc\bcd=Tree$Node@3e532818, D:\android\assets\Assets\abc\cde=Tree$Node@16b07083] 

我会从关键字(通过分割字符串)find父项,然后设置父项。