Languages
[Edit]
EN

Java - get regular files from directory (recursive)

0 points
Created by:
Emelia
237

In this article, we would like to show you how to get all regular files from a directory (including subdirectories) in Java.

Practical example

Project structure:

project/
 ├── one.txt
 └── directory2/
 |      └── two.json
 └── directory3/
        └── three.html

1. Using File.listFiles method.

import java.io.File;

public class Example {

    public static void listFilesInDirectory(File directoryPath) {
        File[] filesList = directoryPath.listFiles();
        for (File file : filesList) {
            if (file.isFile()) {
                System.out.println(file);
            } else {
                listFilesInDirectory(file);
            }
        }
    }

    public static void main(String[] args) {
        File directoryPath = new File("C:\\project");
        listFilesInDirectory(directoryPath);
    }
}

Output: 

C:\project\one.txt
C:\project\directory1\two.json
C:\project\directory2\three.html

2. Using Files.find method.

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

public class Example {

    public static void main(String[] args) throws IOException {
        Files.find(Paths.get("C:\\project"),
                Integer.MAX_VALUE,   // the maximum number of directory levels to search
                (filePath, FileAttributes) -> FileAttributes.isRegularFile())
                .forEach(System.out::println);
    }
}

Output: 

C:\project\one.txt
C:\project\directory1\two.json
C:\project\directory2\three.html

3. Using Files.walk method.

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

public class Example {

    public static void main(String[] args) throws IOException {
        Files.walk(Paths.get("C:\\project"))
                .filter(Files::isRegularFile)
                .forEach(System.out::println);
    }
}

Output: 

C:\project\one.txt
C:\project\directory1\two.json
C:\project\directory2\three.html

See also:

  1. Files.walk()
  2. Files.find()

Java - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join