java递归的方式实现树形目录返回前端页面

递归作为一种算法程序设计语言中广泛应用。 一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。接下来就工作中的一个例子简单练习下:

  1. 创建一个pojo
1
2
3
4
5
6
7
8
java复制代码@Data
Class Directory {
// 目录标签
private String label;

// 子目录
private List<Directory> children;
}
  1. 具体实现类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
java复制代码@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 {
// 绑定到根部录下
if (ROOT_LABEL.equals(rootName)) {
root.setLabel(rootName);
root.setChildren(child);
}

// 遍历目录
File[] files = file.listFiles();
for(File f : files) {
if (f.isFile()) {
// 如果是文件
Directory content = new Directory();
content.setLabel(f.getName());
child.add(content);
} else if (f.isDirectory()) {
// 如果是目录
List<Directory> children = new ArrayList<>(); // 生成子目录用于存放递归目录
Directory content = new Directory();
content.setLabel(f.getName());
content.setChildren(children);
child.add(content);

// 递归目录
fileList(f, f.getName(), children);
}
}
}

return root;
}

}
  1. 运行main方法
1
2
3
4
5
6
7
java复制代码public static void main(String[] args) {
File file = new File("E:\path\tmp\src\fabcar");
List<Directory> childList = new ArrayList<>();
Directory directory = fileList(file, ROOT_LABEL, childList);

System.out.println(JSONUtil.toJsonStr(directory));
}
  1. 运行结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
json复制代码{
"children":[
{
"lable":"fabcar.go"
},
{
"lable":"go.sum"
},
{
"children":[
{
"lable":"moudles.txt"
}
],
"lable":"fabcar.go"
}
],
"lable":"fabcar"
}
1
复制代码

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%