Java中如何利用File类递归的遍历指定目录中的所有文件和文件夹

时间:2022-06-11 12:28:57
package cuiyuee;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class GetAllDirectory {

    public static void showDirectory(File file){
        File[] files = file.listFiles();
        for(File a:files){
            System.out.println(a.getAbsolutePath());
            if(a.isDirectory()){
                showDirectory(a);
            }
        }
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        File file = new File("F:\\java");
        showDirectory(file);
    }

}

执行结果如下

F:\java\childDirectory
F:\java\childDirectory\cuiyuee1.txt
F:\java\cuiyuee.txt
F:\java\songbo.txt