递归打印多级目录

话不多说,直接上代码:

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

            }
发布了26 篇原创文章 · 获赞 2 · 访问量 378

猜你喜欢

转载自blog.csdn.net/qq_41628448/article/details/104531846
今日推荐