O'Reilly logo

Core Java® Volume II—Advanced Features, Ninth Edition by Gary Cornell, Cay S. Horstmann

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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")) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required