打印目录树形结构

遇到的小问题,也就记录到这里吧。

要求是打印指定目录的树形结构。

上代码

public class FileTree {

    public static void main(String[] args) {
        if (args[0] == null) {

            throw new RuntimeException("args0 is null");
        }
        File file = new File(args[0]);

        if (!file.exists()) {
            throw new RuntimeException("file not exits");
        }
        treeFile(file, 0);

    }

    public static void treeFile(File file, int n) {
        File[] files = file.listFiles();

        for (File f : files) {

            for (int i = 0; i < n; i++) {
                System.out.print("-");
            }
            System.out.println(f.getName());
            if (f.isDirectory()) {
                treeFile(f, n + 1);
            }

        }
    }

}

将其导出为可运行jar包,运行命令 java -jar treefile.jar “目录”即可。

原创博文,未经许可不得转载,转载请注明出处。
原文地址:https://www.cnblogs.com/Think-007/p/8204010.html