java 显示文件夹结构

来源:互联网 发布:心事谁人知 黄乙玲 编辑:程序博客网 时间:2024/05/19 23:11

今天看到一个文件显示的代码,想自己写个,先来看看运行结果

下面贴代码 ,注释都有

public class FolderList {/** * 显示文件结构 */private static int spaceNum = 3;public static void main(String[] args) {File folder = new File("F:/test");System.out.println(folder.getName());//打印根目录showFiles(spaceNum,1,folder.listFiles());}//显示文件:深度优先遍历(deepth为文件夹深度)private static void showFiles(int sapce,int deepth,File[] files) {StringBuffer spaceStr = new StringBuffer();int tmp = deepth;//保存输入的deepth值,放在deepth--操作丢失数据//添加空格 ,树形结构调整for(int i=0;i<sapce;i++){if((i%spaceNum==0)&&(deepth>=0)&&(i!=0)){spaceStr.append("|");deepth-- ;}spaceStr.append(" ");}spaceStr.append("|─");for(File file : files){System.out.println(spaceStr+file.getName());//如果是文件夹,继续遍历if(file.isDirectory()){showFiles(sapce+spaceNum,tmp+1,file.listFiles());}}}}


原创粉丝点击