1.6.6. Iterating over the Files in a Directory

The old File class had a method for getting an array of all files in a directory, but that led to poor performance with directories holding huge numbers of files. For that reason, the Files class has a method that yields an Iterable object instead. Here is how you use it:

try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir)) {    for (Path entry : entries)       Process entries }

The try-with-resources block ensures that the directory stream is properly closed.

There is no specific order in which the directory entries are visited.

You can filter the files with a glob pattern:

try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir, "*.java")) ...

Get Core Java® Volume II—Advanced Features, Ninth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.