EN
Java - list all files from directory
0 points
In this article, we would like to show you how to list all file names from the directory in Java.
Quick solution:
xxxxxxxxxx
1
File[] files = new File(path).listFiles(File::isFile); // get array of files
In this example, we use listFiles()
method and check if the file is a file (not a directory) to list only files from the directory specified by path
.

Code example:
xxxxxxxxxx
1
import java.io.File;
2
import java.util.Objects;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
8
String path = "C:\\projects\\example";
9
File[] files = new File(path).listFiles(File::isFile); // array of files
10
11
File[] list = Objects.requireNonNull(files); // creates list if files!= null
12
13
for (File item : list) {
14
System.out.println(item.getName());
15
}
16
}
17
}
Result:
xxxxxxxxxx
1
file1.txt
2
file2.json
3
file3.pdf
Note:
To get full file paths instead of file names remove
getName()
fromitem.getName()
inside for loop.Result:
xxxxxxxxxx
1C:\projects\example\file1.txt
2C:\projects\example\file2.json
3C:\projects\example\file3.pdf