Get All Files from Current Directory in Java

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

Here, we discuss two below approaches:
1. Using simple File class
2. NIO Files.list API

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

In this example, we list all the files from the current directory and if this directory has other nested sub-directories, list files from them also using recursion pattern. Note that we are using a dot(.) which denotes the current working directory:
package net.javaguides.corejava.io;

import java.io.File;

public class GetFiles {

    public static void main(String[] args) {
        File curDir = new File(".");
        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

Using NIO Files. list API - Get All Files from Current Directory

In this example, we only list files from the current directory (not from sub-directories):
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class GetFiles {

    public static void main(String[] args) throws IOException {

        Files.list(Paths.get("."))
            .forEach(path - > System.out.println(path));
    }
}
Output:
JavaCopyFile.java
JavaCreateFile.java
JavaDeleteFile.java
JavaGetFileOwner.java
JavaMoveFile.java
JavaReadFile.java
JavaWriteFile.java

Comments