Java Files.list
last modified January 27, 2024
Java Files.list tutorial shows 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.
Files.list current directory
The first example lists the current directory.
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesListEx { public static void main(String[] args) throws IOException { Files.list(Paths.get(".")) .forEach(path -> System.out.println(path)); } }
The dot symbol represents the current working directory. We get the path object
with Paths.get
.
Files.list directories
The following example lists directories in the user's home directory.
package com.zetcode; import java.io.File; import java.io.IOException; import java.nio.file.Files; public class FilesListEx2 { public static void main(String[] args) throws IOException { var homeDir = System.getProperty("user.home"); Files.list(new File(homeDir).toPath()) .filter(path -> path.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
.
Files.list by file extensions
The next program lists all PDF files.
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesListEx3 { public static void main(String[] args) throws IOException { var homeDir = System.getProperty("user.home") + System.getProperty("file.separator") + "Downloads"; Files.list(Paths.get(homeDir)).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.
Files.list count files
We count the number of PDF files.
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesListEx4 { public static void main(String[] args) throws IOException { var homeDir = System.getProperty("user.home") + System.getProperty("file.separator") + "Downloads"; var nOfPdfFiles = Files.list(Paths.get(homeDir)).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 all Java tutorials.