2

How would I go around recursively traversing and storing a directory structure? I'm writing an app to load up two folders, traverse their structure, show the differences in a GUI, and synchronize the two if prompted to do so.

Background: I get the basic principle(use a tree; if a file, append it to the calling dir, if a dir, append and recursively call the function on it), but all the implementations I found are just a little bit off from what I need, or they spit out a NullPointerException which I can't fix, as I don't understand what exactly they do. I think I'm stuck on a technicality or a quirk somewhere in the recursive calls or in creating child nodes.

Edit: This is a node class i copied from somewhere. I recently deleted my old putIntoTree function, and I'm currently working on a new one. I'm stuck on how exactly the children/parent creation works.

import java.nio.file.Path;
import java.util.*;

abstract class TreeNode implements Iterable<TreeNode> {

    private Set<TreeNode> children;
    public Path path;

    public TreeNode(Path path) {
        children = new HashSet<TreeNode>();
        this.path = path;
    }

    public boolean addChild(TreeNode n) {
        return children.add(n);
    }

    public boolean removeChild(TreeNode n) {
        return children.remove(n);
    }

    public Iterator<TreeNode> iterator() {
        return children.iterator();
    }
}

Edit: I'm trying to get this tree structure to work in there, but I'm a bit baffled at how exactly pointy brackets and generics work. It says "cannot resolve symbol[whatever is after the in my own attempt at defining a method]"

public class Tree<T> {
    private Node<T> root;

    public Tree(T rootData) {
        root = new Node<T>();
        root.data = rootData;
        root.children = new ArrayList<Node<T>>();
    }

    public static class Node<T> {
        private T data;
        private Node<T> parent;
        private List<Node<T>> children;
    }
}
Sargon1
  • 854
  • 5
  • 17
  • 48
  • Do you have a code sample with a specific issue ? Your algorithm is a good start :) – Gaël J Oct 08 '15 at 19:03
  • Not really, unfortunately. I'm currently trying to write a Tree class that would contain a TreeNode root (meaning without any parent) and the Paths to the files, stored in other TreeNodes, and will be filled with calling fillTree on the Tree itself, which will then call the algorithm above on the root as the parent as the actual topmost dir as the place to start, so that the topmost dir is appended to the root. – Sargon1 Oct 09 '15 at 09:15

0 Answers0