来自文件路径的 Java JTree 目录结构 [英] Java JTree directory structure from file paths
问题描述
我一直在努力解决这个问题,所以也许你们中的一些人可以帮助我.我有一个带有完整路径的文件列表(这些只是文件在另一台机器上的字符串),例如:
I've been trying to get my head around this so maybe some of you can help me. I have a list of files with their full paths (these are just strings the files are on another machine), e.g:
C:acfile1.txt
C:acfile2.txt
C:adfile3.txt
C:efile4.txt
我想创建一个 Jtree 来显示这样的目录结构:
I want to create a Jtree to show the directory structure like this:
C:
a
b
c
file1.txt
file2.txt
d
file3.tct
e
file4.txt
我一直在分隔符上拆分字符串,所以我最终得到了一个数组列表,例如:
I've been spliting the string on the seperator so I end up with a list of arrays like:
"C:","a","b","c","file1.txt"
"C:","a","b","c","file2.txt"
"C:","a","d","file3.txt"
"C:","e","file4.txt"
现在我想一次为它们添加一个索引,但如果该值已存在于该级别,则跳到下一个索引.即它会添加第一个数组,然后在第二个数组上它会进入树的第 0 层,那里已经存在一个C:",所以移到树的第 1 层和数组的索引 1.我遇到的问题是我不确定如何以这种方式导航树.
Now I want to add them an index at a time but if the value already exists at that level then to skip to the next index. i.e it would add the first array then on the second array it would go on level 0 of the tree there already exists a "C:" so move onto level 1 of the tree and index 1 of the array. The issues that I have is that Im not sure how to navigate the tree in such a way.
有任何建议和/或替代实施方案吗?
Any suggestions and or alternative implementations?
推荐答案
让 File
做解析和维护路径的工作.如果你想在JTree
中显示文件,你不妨创建一个相应的TreeModel
,比如FileTreeModel
,引用此处.因为它实现了 TreeModel
,所以它可以被设置为一个 JTree
的模型,然后你就会拥有一个普通的旧标准 JTree
".您可以在任何挂载的文件系统中使用任何 File
作为根,例如:
Let File
do the work of parsing and maintaining paths. As you want to display the files in a JTree
, you might as well create a corresponding TreeModel
such as FileTreeModel
, cited here. Because it implements TreeModel
, it can "be set as a JTree
's model and then you'd have a plain old standard JTree
." You can use any File
in any mounted file system as the root, for example:
TreeModel model = new FileTreeModel(new File(System.getProperty("user.dir")));
JTree tree = new JTree(model);
这篇关于来自文件路径的 Java JTree 目录结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!