문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top