Java Files.list
last modified July 6, 2024
In this article we show how to list files in Java with Files.list
.
Files.list
returns a lazily populated stream of directory elements.
The listing is not recursive.
The elements of the stream are Path
objects.
Listing current directory
The first example lists the current directory.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; void main() throws IOException { var path = Paths.get("."); try (var files = Files.list(path)) { files.forEach(System.out::println); } }
The dot symbol represents the current working directory. We get the path object
with Paths.get
.
Listing directories in home directory
The following example lists directories in the user's home directory.
import java.io.File; import java.io.IOException; import java.nio.file.Files; void main() throws IOException { var homeDir = System.getProperty("user.home"); var path = new File(homeDir).toPath(); try (var files = Files.list(path)) { files.filter(p -> p.toFile().isDirectory()) .forEach(System.out::println); } }
We convert the path object to a File
with toFile
and call the isDirectory
method. The stream is filtered
with filter
.
Listing by file extensions
The next program lists all PDF files.
import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Paths; void main() throws IOException { var homeDir = System.getProperty("user.home") + FileSystems.getDefault().getSeparator() + "Downloads"; try (var files = Files.list(Paths.get(homeDir))) { files.filter(path -> path.toString().endsWith(".pdf")) .forEach(System.out::println); } }
The program lists PDF files in the Downloads directory. The path object is
converted to a string and we call endsWith
on the string to
check if it ends with pdf
extension.
Counting files
We count the number of PDF files.
import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Paths; void main() throws IOException { var homeDir = System.getProperty("user.home") + FileSystems.getDefault().getSeparator() + "Downloads"; try (var files = Files.list(Paths.get(homeDir))) { var nOfPdfFiles = files.filter(path -> path.toString() .endsWith(".pdf")).count(); System.out.printf("There are %d PDF files", nOfPdfFiles); } }
The number of files is determined with count
.
Source
In this article we have used Files.list
to list the directory
contents.
Author
List Main.java tutorials.