java用递归输出目录结构

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);
            }
        }
    }
}

结果:

 

posted @ 2018-09-07 16:06  那心之所向  阅读(271)  评论(0编辑  收藏  举报