1

I'm trying to build a TreeModel for a Java application. Since I need to serialize it and send it via an ObjectOutputStream, I'm trying to use the DefaultTreeModel because it implements the Serializable interface.

Ok, I think I'm fine with that.

My question is: Now, how can I build a DefaultTreeModel containing a directory (passed as argument, a DefaultMutableTreeNode I guess ?) and all its files and subdirectories ?

I achieved that with a JTree but it seems not to be Serializable so now I'm stucked because I'm unable to understand the doc examples.

thibaultcha
  • 1,320
  • 2
  • 15
  • 27

1 Answers1

2

File is Serializable, and a FileTreeModel that implements TreeModel is straightforward, as mentioned here. You can traverse a tree rooted in File f using code like this:

private void ls(File f) { 
    File[] list = f.listFiles();
    for (File file : list) {
        if (file.isDirectory()) ls(file);
        else handle(file);
    }
}

Also consider Bloch's suggestion, Item 75, "Do not accept the default serialized form without first considering whether it is appropriate."

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • I do not want to traverse anything, I just need a TreeModel (like your FileTreeModel example) that I can build by passing a root directory, and Serialize (what your example doesn't seem to do). As simple as that. Nothing else. – thibaultcha Feb 13 '13 at 22:45
  • Then just add `implements Serializable` and a `static final long` field named `serialVersionUID`. The single attribute, `root`, is already `Serializable`. – trashgod Feb 13 '13 at 22:58
  • Fine ! I tried it already but I was facing something strange so I wasn't certain if it was my `TreeModel` or not. I persevered with this (yours) solution and found out the bug was due something else. So now it's working, thank you ! – thibaultcha Feb 13 '13 at 23:26