Languages
[Edit]
EN

Java - get regular files from directory (recursive)

0 points
Created by:
Emelia
517

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()
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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