java中递归遍历文件夹下所有文件

java遍历文件夹下所有文件

public class Test {
    public static void main(String [] args) {
        traverseFolder("D:/eclipse/eclipseWorkspace/fileupload/scheme1/");
    }
    
    public static  void traverseFolder(String path) {

        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                System.out.println("文件夹是空的!");
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        traverseFolder(file2.getAbsolutePath());
                    } else {
                        System.out.println("文件:" + file2.getAbsolutePath());
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }
}

测试文件夹

查看遍历输出是否正确

 

posted @ 2019-08-01 10:05  余暗  阅读(3371)  评论(0编辑  收藏  举报