ubergam3r
ubergam3r

Reputation: 189

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:\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. 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?

Upvotes: 3

Views: 14102

Answers (3)

murison
murison

Reputation: 3983

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.

Upvotes: 1

trashgod
trashgod

Reputation: 205775

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

image

Upvotes: 7

SJuan76
SJuan76

Reputation: 24780

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.

Upvotes: 0

Related Questions