java打印树形目录结构

import java.io.File;


public class MainTest {
    public static void main(String[] args) {
        String dirname = "D:\\menu";
        menu(dirname, 0);
    }
    public static void menu(String dirname, int padding){
        File file = new File(dirname);
        if(file.isDirectory()){
            System.out.println(padding_n(padding)+"目录: " + dirname);
            String s[] = file.list();
            for (int i=0; i<s.length; i++){
                File f = new File(dirname + "/" + s[i]);
                if(f.isDirectory()){
                    menu(dirname+"\\"+s[i], padding+4);
                }else{
                    System.out.println(padding_n(padding+4)+"文件:"+s[i]);
                }
            }
        }
    }
    public static String padding_n(int n){
        StringBuffer space = new StringBuffer("");
        for (int i=0; i<n; i++){
            space.append(" ");
        }
        return space.toString();
    }
}

 

posted @ 2019-03-11 16:14  那天ws  阅读(1412)  评论(0编辑  收藏  举报