递归打印多级目录

Deadly 提交于 2020-02-27 13:11:49

话不多说,直接上代码:

import java.io.File;

public class demo2PrintDir {
    public static void main(String[] args) {
        String s = new String("E:\\demo");
        printAllFiles(s);

    }
    public static void printAllFiles(String pathname){
        File file = new File(pathname);//创建File
        File[] files = file.listFiles();//把当前File对象下所有的文件夹或目录
        for (File file1: files){
            if (file1.isFile()){//递归的终止条件是:当前File为文件
                System.out.println(file1.getAbsolutePath());
            }
            else{//当前File为目录,则,打印当前File的子文件的递归目录
                //String s = file1.getPath();
                //printAllFiles(s);
                //printAllFiles(file1.getPath());
                System.out.println(file1.getAbsolutePath());
                printAllFiles(file1.getAbsolutePath());
            }

        }


    }
}

当选择只打印java文件的时候,当File为目录时,不打印。为文件时,判断是否以Java结尾

if else结构修改为`

if (file1.isFile()){//递归的终止条件是:当前File为文件
                if(file1.getAbsolutePath().endsWith(".java")){
                    System.out.println(file1.getAbsolutePath());再次判断
                }
            }
            else{//当前File为目录,则,打印当前File的子文件的递归目录
                //String s = file1.getPath();
                //printAllFiles(s);
                //printAllFiles(file1.getPath());
                //System.out.println(file1.getAbsolutePath())备注掉
                printAllFiles(file1.getAbsolutePath());

            }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!