Get All Files from Directory and Sub-directories in Java

In this example, I show you how to get all files from the directory and its subdirectories in Java.

Get All Files from Directory and Sub-directories in Java Example

In this example, we list all the files from it and if this directory has other nested sub-directories, list files from them also using recursion pattern.
package net.javaguides.corejava.io;

import java.io.File;

public class GetFiles {

    public static void main(String[] args) {
        File curDir = new File("C:\\Project_Work\\AICWebClient\\workspace\\core-java\\src\\net\\javaguides\\corejava\\io");
        getAllFiles(curDir);
    }
    private static void getAllFiles(File curDir) {

        File[] filesList = curDir.listFiles();
        for (File f: filesList) {
            if (f.isDirectory())
                getAllFiles(f);
            if (f.isFile()) {
                System.out.println(f.getName());
            }
        }

    }
}
Output:
JavaCopyFile.java
JavaCreateFile.java
JavaDeleteFile.java
JavaGetFileOwner.java
JavaMoveFile.java
JavaReadFile.java
JavaWriteFile.java



Comments