Cover Page by Gary Cornell, Cay S. Horstmann

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required