DirectoryStream Class

Package: java.nio.file

The DirectoryStream class represents a collection of path objects contained in a directory. The DirectoryStream class implements the Iterable interface, which means that it can be used to read the contents of a directory using an enhanced for statement.

To create a DirectoryStream object, use the static newDirectoryStream method of the Files class. For more information, see Files Class.

Method

Method

Description

Iterator iterator()

Returns an Iterator object, which can be used to iterate the paths in the directory stream.

Here’s an example that retrieves the contents of a directory and prints each item on the console:

Path c = Paths.get(“C:\\myfolder”);

try

{

DirectoryStream<Path> stream

= Files.newDirectoryStream(c);

for (Path entry: stream)

System.out.println(entry.toString());

}

catch (Exception e)

{

System.out.println(“Error: “ + e.getMessage());

}

Get Java For Dummies Quick Reference 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.