Listing All Files in a Directory

It’s pretty simple to use the File class’s list method to list all filenames in a directory. To get all the files instead of just their names, we can use the listFiles method. That’s easy, but the challenge is how to proceed once we get the list. Rather than the long-winded traditional external iterator, we can use the elegant functional-style facility to iterate through the list. To achieve this, we have to reach out to the JDK’s new CloseableStream interface, along with some related higher-order convenience functions.

Here’s the code to list the names of all the files in the current directory.

compare/fpij/ListFiles.java
 
Files.list(Paths.get(​"."​))
 
.forEach(​System​.out::println);

To list files in a different ...

Get Functional Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.