简体   繁体   中英

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), eg:

C:\a\b\c\file1.txt
C:\a\b\c\file2.txt
C:\a\d\file3.txt
C:\e\file4.txt

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"

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. ie 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?

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);

图像

I'm not sure if FileTreeModel is the best way - it scans entire directories. From what you wrote, I guess you only want to display paths from your list.
You can achieve it by using TreePathsTreeModel described here: How I Show Windows Registry in jTree?
You just have to to convert filepaths from strings into TreePath objects.

First, sort the Strings (before splitting them).

How to process the first line is obvious and I won't comment on it. In the second line, search the already built tree and check if the nodes already exist. After you find one that does not exist, follow the procedure done in the first line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM