输出的结构类似于linux下的tree命令如下:
原创不易,转载请注明出处:java打印文件树的代码
package com.zuidaima.file;
import java.io.File;
import java.util.Arrays;
import org.junit.Test;
public class ListDir2 {
int indentLevel = -1;
String htmlPath = "";
@Test
public void listPath() {
File path = new File("C:/zuidaima/");
listPath(path);
}
public void listPath(File path) {
File files[];
indentLevel++;
files = path.listFiles();
Arrays.sort(files);
for (int i = 0, n = files.length; i < n; i++) {
for (int indent = 0; indent < indentLevel; indent++) {
System.out.print(" ");
}
File file = files[i];
if (file.isDirectory()) {
System.out.println(file.getAbsolutePath());
} else {
System.out.println(file.getName());
}
if (files[i].isDirectory()) {
listPath(files[i]);
}
}
indentLevel--;
}
}
代码下载地址: http://www.zuidaima.com/share/1550463223532544.htm