Today, i show you some Java 8 list files in directory examples using Java 8 APIs along with Files.list() and DirectoryStream. We will do some tasks such as, list all files and sub-directories, list only files inside directory, list files of certain extention and recursively list all files within a directory.
Let’s begin:
List all files and sub-directories
1 2 3 4 5 |
// List all files and sub-directories //1st way Files.list(Paths.get(".")).forEach(System.out::println); //2nd way Files.newDirectoryStream(Paths.get(".")).forEach(System.out::println); |
Noticed that if we are working with a large directory, then using DirectoryStream actually make code faster.
List only files inside directory
1 2 3 4 5 |
// filter file only //1st way Files.list(Paths.get(".")).filter(Files::isRegularFile).forEach(System.out::println); //2nd way Files.newDirectoryStream(Paths.get("."), path -> path.toFile().isFile()).forEach(System.out::println); |
List files of certain extention
1 2 3 |
Files.newDirectoryStream(Paths.get("."), path -> path.toString().endsWith(".java")) .forEach(System.out::println); |
Recursively list all files within a directory
1 |
Files.walk(Paths.get(".")).forEach(System.out::println); |
Dem program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class ListFilesInDirectory { public static void main(String args[]) throws IOException { // Get all files and sub-directories Files.list(Paths.get(".")).forEach(System.out::println); Files.newDirectoryStream(Paths.get(".")).forEach(System.out::println); // filter file only Files.list(Paths.get(".")).filter(Files::isRegularFile).forEach(System.out::println); Files.newDirectoryStream(Paths.get("."), path -> path.toFile().isFile()).forEach(System.out::println); // filter file java only Files.newDirectoryStream(Paths.get("."), path -> path.toString().endsWith(".java")) .forEach(System.out::println); // find all hidden files final File[] files = new File(".").listFiles(File::isHidden); Stream.of(files).forEach(System.out::println); //Recursively list all files within a directory Files.walk(Paths.get(".")).forEach(System.out::println); } } |
Output
That’s all about the Java 8 list files in directory.
References
DirectoryStream (Java Platform SE 8 )
Download the complete source code, click link below
ListFilesInDirectory.zip (237 downloads)