Search code examples
javajstree

Creation of jstree data from java for a given folder x levels down


Given a folder I would like to construct tree of children down to x levels and render as jstrees html format (i.e ul, li so on) https://www.jstree.com/docs/html/ so that server files can be viewed remotely over webbrowser.

What is the best way to do this ?

Has anyone created a lib tieing java and jstree to do it, seems I cant be the first person to want to do this.


Solution

  • first, I'd like to point out that jsTree also accepts JSON as data input and not only raw html(https://www.jstree.com/docs/json/)

    It looks like this:

    // Expected format of the node (there are no required fields)
    {
      id          : "string" // will be autogenerated if omitted
      text        : "string" // node text
      icon        : "string" // string for custom
      state       : {
        opened    : boolean  // is the node open
        disabled  : boolean  // is the node disabled
        selected  : boolean  // is the node selected
      },
      children    : []  // array of strings or objects
      li_attr     : {}  // attributes for the generated LI node
      a_attr      : {}  // attributes for the generated A node
    }
    

    To produce such a JSON format (or the equivalent in HTML form) can be done fairly easely using a recursive function. Here would be the pseudo-code:

    class Node {
      String id;
      String text;
      // ...
      List<Node> children;
    }
    
    class Filesystem {
    
       Node browse(File path, int depth) {
           Node node = new Node(file);
           if( depth > 0 ) {
              for(File f : file.listFiles()) {
                 Node child = browse(f, depth - 1);
                 node.children.add(child);
              }
           }
           return node;
       }
    }
    

    It's not a copy-paste solution, but it should fairly straighforward to obtain one.