zoukankan      html  css  js  c++  java
  • java遍历目录结构

    打印一个目录的结构,一个目录可以看成一棵树,因此算法的核心是树的遍历,树的遍历又有前序遍历、中序遍历和后序遍历,本文章中使用前序遍历,另外由于树的定义具有递归性质,因此算法采用递归的方式,程序如下:

    public static void printDirectory(File f,int depth){
    		if(!f.isDirectory()){//如果不是目录,则打印输出
    			System.out.println(getTap(depth)+f.getName());
    		}else{
    			File[] fs=f.listFiles();
    			System.out.println(getTap(depth)+f.getName());
    			depth++;
    			for(int i=0;i<fs.length;++i){
    				File file=fs[i];
    				printDirectory(file,depth);
    			}
    		}
    }
    

    其中getTap方法是辅助方法,目的是使输出具有一定的层次关系,方法定义如下:

    private static String getTap(int depth){
    		StringBuffer tap=new StringBuffer();
    		for(int i=0;i<depth;i++){
    			tap.append("------");
    		}
    		return tap.toString();
    }
    
    测试目录是test,结构如下图所示:

    测试程序就是简单的调用printDirectory方法,如下所示:

    public static void main(String[] args){
    		File f=new File("test");
    		printDirectory(f,0);
    }
    
    程序的输出如下:

    test
    ------11
    ------------111
    ------------------1111.txt
    ------------------1112.txt
    ------------112.txt
    ------12
    ------------123.txt
    ------13.txt

  • 相关阅读:
    Linux- 恢复.swp文件
    codeforces contest 1111
    bzoj2589【 Spoj 10707】 Count on a tree II
    20190129模拟题
    loj6070【山东集训第一轮Day4】基因
    bzoj4784【zjoi2017】仙人掌
    bzoj4520【cqoi2016】K远点对
    【学习笔记】BEST定理
    bzoj2441【中山市选】小W的问题
    bzoj3203【sdoi2013】保护出题人
  • 原文地址:https://www.cnblogs.com/sunzhenxing19860608/p/1965421.html
Copyright © 2011-2022 走看看