February 2014
Intermediate to advanced
160 pages
4h 59m
English
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 ...