Home > Blockchain >  How can I print the directories first and then the files (tree)
How can I print the directories first and then the files (tree)

Time:11-28

This part of class is responsible for create directories and files and append its.

public class TreeNode<T> implements Iterable<TreeNode<T>> {

    public T data;
    public TreeNode<T> parent;
    public List<TreeNode<T>> children;

    public boolean isRoot() {
        return parent == null;
    }

    private List<TreeNode<T>> elementsIndex;

    public TreeNode(T data) {
        this.data = data;
        this.children = new LinkedList<TreeNode<T>>();
        this.elementsIndex = new LinkedList<TreeNode<T>>();
        this.elementsIndex.add(this);
    }

    public TreeNode<T> addChild(T child) {
        TreeNode<T> childNode = new TreeNode<T>(child);
        childNode.parent = this;
        this.children.add(childNode);
        this.registerChildForSearch(childNode);
        return childNode;
    }

    private void registerChildForSearch(TreeNode<T> node) {
        elementsIndex.add(node);
        if (parent != null)
            parent.registerChildForSearch(node);
    }

    @Override
    public String toString() {
        return data != null ? data.toString() : "[data null]";
    }

    @Override
    public Iterator<TreeNode<T>> iterator() {
        TreeNode<T> iter = new TreeNode<T>((T) this);
        return (Iterator<TreeNode<T>>) iter;
    }

    public static TreeNode<File> createDirTree(File folder) {
        if (!folder.isDirectory()) {
            throw new IllegalArgumentException("folder is not a Directory");
        }
        TreeNode<File> DirRoot = new TreeNode<File>(folder);
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                appendDirTree(file, DirRoot);
            } else {
                appendFile(file, DirRoot);
            }}
        return DirRoot;
    }

    public static void appendDirTree(File folder, TreeNode<File> DirRoot) {
        DirRoot.addChild(folder);
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                appendDirTree(file, DirRoot.children.get(DirRoot.children.size() - 1));
            } else {
                appendFile(file, DirRoot.children.get(DirRoot.children.size() - 1));
            }} }

    public static void appendFile(File file, TreeNode<File> filenode) {
        filenode.addChild(file);
    }

The problem is that in this state of code the files and directories are printed like this:

rootFolder   
├─ Folder1 
│  ├─ subFolder1 
│  │  ├─ a.txt  
│  │  ├─ b.txt 
│  │  ├─ c.txt  
│  │  └─ d.txt  
│  ├─ subFolder2  
│  │  ├─ a.txt  
│  │  ├─ B.txt  
│  │  ├─ c.txt  
│  │  └─ D.txt  
│  ├─ subFolder3 
│  │  ├─ A.txt  
│  │  ├─ b.txt  
│  │  ├─ C.txt  
│  │  └─ d.txt  
│  └─ subFolder4 
│      ├─ a.txt  
│      ├─ b.txt 
│      ├─ c.txt 
│      └─ d.txt 
├─ File1.txt  
├─ Folder2  
│  ├─ a.txt 
│  ├─ b.txt 
│  ├─ c.txt 
│  └─ d.txt 
└─ File2.txt

but I need the directories to go first and then the files: File1.txt near File2.txt. I try to find where is the problem but to no avail. What I need to change and where in code to get the desired result?

CodePudding user response:

The problem is the order in which you append the child-trees.

As the Java Documentation says for .listFiles():

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

So you need to sort the files before appending them.

Here a possible Solution for the methods createDirTree and appendDirTree.

(Note: the sorting is only based on if its a directory or not. If you need another custom sorting, you need to adapt the Comparator`)

public static TreeNode<File> createDirTree(File folder) {
  if (!folder.isDirectory()) {
    throw new IllegalArgumentException("folder is not a Directory");
  }

  List<File> children = Arrays.asList(folder.listFiles());
  children.sort(Comparator.comparing(file -> file.isDirectory() ? -1 : 1));

  TreeNode<File> DirRoot = new TreeNode<File>(folder);
  for (File file : children) {
    if (file.isDirectory()) {
      appendDirTree(file, DirRoot);
    } else {
      appendFile(file, DirRoot);
    }}
  return DirRoot;
}

public static void appendDirTree(File folder, TreeNode<File> dirRoot) {
  dirRoot.addChild(folder);

  List<File> children = Arrays.asList(folder.listFiles());
  children.sort(Comparator.comparing(file -> file.isDirectory() ? -1 : 1));

  for (File file : children) {
    if (file.isDirectory()) {
      appendDirTree(file, dirRoot.children.get(dirRoot.children.size() - 1));
    } else {
      appendFile(file, dirRoot.children.get(dirRoot.children.size() - 1));
    }
  }
}

There are several ways to achieve this. E.g. you can also use streams. See the example for createDirTree below:

public static TreeNode<File> createDirTree(File folder) {
  if (!folder.isDirectory()) {
    throw new IllegalArgumentException("folder is not a Directory");
  }
  TreeNode<File> DirRoot = new TreeNode<File>(folder);
  
  Arrays.stream(folder.listFiles())
      .sorted(Comparator.comparing(f -> (f.isDirectory() ? 1 : -1)))
      .forEach(file -> {
        if (file.isDirectory()) {
          appendDirTree(file, DirRoot);
        } else {
          appendFile(file, DirRoot);
        }
      });
  return DirRoot;
}
  • Related