EN
Java - get regular files from directory (recursive)
0
points
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