Search code examples
javaswingserializationtreemodel

How to build a Serializable TreeModel containing files and subdirectories?


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.


Solution

  • 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."