java用递归输出目录结构

时间:2021-10-08 18:11:21
package com.janson.day20180827;

import java.io.File;

public class TestTreeStructureDirectory {
public static void main(String[] args) {
File file = new File("D:/A");
System.out.println(file.getName());
new TestTreeStructureDirectory().treeDir(file,1);
} private void treeDir(File file,int level) {
String preStr = "";
for(int i=0; i<level; i++) {
preStr += " ";
} File[] f = file.listFiles();
//for (int i=0; i<f.length; i++) 下面用foreach循环或者加强型循环实现
for (File item:f) {
System.out.println(preStr + item.getName());
if(item.isDirectory()) {
treeDir(item,level+1);
}
}
}
}

结果:

java用递归输出目录结构