Work encountered a demand, considering that such a program on the Internet will be a lot of people want to take directly from the Internet, the result of looking for a long time did not find what they want, simply write their own, the implementation logic is as follows:

import cn.hutool.json.JSONUtil;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component
public class FileDirectory {

    private static Directory root = new Directory();

    private static String ROOT_LABEL = "fabcar";

    public static Directory fileList(File file, String rootName, List<Directory> child) {
        if (file.isFile() || 0 == file.listFiles().length) {
            return null;
        } else {
            // bind to root to record
            if (ROOT_LABEL.equals(rootName)) {
                root.setLabel(rootName);
                root.setChildren(child);
            }

            // Traverse the directory
            File[] files = file.listFiles();
            for(File f : files) {
                if (f.isFile()) {
                    // If it is a file
                    Directory content = new Directory();
                    content.setLabel(f.getName());
                    child.add(content);
                } else if (f.isDirectory()) {
                    // If it is a directory
                    List<Directory> children = new ArrayList<>(); // Generate subdirectories to hold recursive directories
                    Directory content = new Directory();
                    content.setLabel(f.getName());
                    content.setChildren(children);
                    child.add(content);

                    // Recursive directoryfileList(f, f.getName(), children); }}}return root;
    }

    public static void main(String[] args) {
        File file = new File("E:\\path\\tmp\\src\\fabcar");
        List<Directory> childList = newArrayList<>(); Directory directory = fileList(file, ROOT_LABEL, childList); System.out.println(JSONUtil.toJsonStr(directory)); }}Copy the code
@Data
class Directory {

    // Directory label
    private String label;

    / / subdirectory
    private List<Directory> children;

}
Copy the code

The effect is as follows: