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.
Project structure:
xxxxxxxxxx
1
project/
2
├── one.txt
3
└── directory2/
4
| └── two.json
5
└── directory3/
6
└── three.html
xxxxxxxxxx
1
import java.io.File;
2
3
public class Example {
4
5
public static void listFilesInDirectory(File directoryPath) {
6
File[] filesList = directoryPath.listFiles();
7
for (File file : filesList) {
8
if (file.isFile()) {
9
System.out.println(file);
10
} else {
11
listFilesInDirectory(file);
12
}
13
}
14
}
15
16
public static void main(String[] args) {
17
File directoryPath = new File("C:\\project");
18
listFilesInDirectory(directoryPath);
19
}
20
}
Output:
xxxxxxxxxx
1
C:\project\one.txt
2
C:\project\directory1\two.json
3
C:\project\directory2\three.html
xxxxxxxxxx
1
import java.nio.file.Files;
2
import java.nio.file.Paths;
3
import java.io.IOException;
4
5
public class Example {
6
7
public static void main(String[] args) throws IOException {
8
Files.find(Paths.get("C:\\project"),
9
Integer.MAX_VALUE, // the maximum number of directory levels to search
10
(filePath, FileAttributes) -> FileAttributes.isRegularFile())
11
.forEach(System.out::println);
12
}
13
}
Output:
xxxxxxxxxx
1
C:\project\one.txt
2
C:\project\directory1\two.json
3
C:\project\directory2\three.html
xxxxxxxxxx
1
import java.nio.file.Files;
2
import java.nio.file.Paths;
3
import java.io.IOException;
4
5
public class Example {
6
7
public static void main(String[] args) throws IOException {
8
Files.walk(Paths.get("C:\\project"))
9
.filter(Files::isRegularFile)
10
.forEach(System.out::println);
11
}
12
}
Output:
xxxxxxxxxx
1
C:\project\one.txt
2
C:\project\directory1\two.json
3
C:\project\directory2\three.html