Chthonic Project
Chthonic Project

Reputation: 8346

In Java 8 Stream API, what's the difference between a DirectoryStream<Path> and Stream<Path>?

I want to return a stream of paths (these are files located in a certain directory). My initial approach was this:

DirectoryStream getFiles(Path dir) throws IOException {
    Files.newDirectoryStream(dir);
}

... but, I would like to know the difference between the above snippet and this second one:

Stream<Path> getFiles(Path dir) throws IOException {
    Spliterator<Path> spl = Files.newDirectoryStream(dir).spliterator();
    return StreamSupport.stream(spl, false);
}

Both DirectoryStream and Stream are sub-interfaces of AutoCloseable, but beyond that, they seem to be designed for different purposes.

To be more precise, my question is this:

What are the conceptual and functionality-based differences between DirectoryStream and Stream interfaces in Java-8?

Upvotes: 2

Views: 1763

Answers (1)

shazin
shazin

Reputation: 21883

What are the conceptual and functionality-based differences between DirectoryStream and Stream interfaces in Java-8?

Java Stream API is general purpose API designed and implemented provide immutable, lazy, functional/declarative style of coding with any stream of objects. This is not specific for one scope and has mechanisms to filter, transform, aggregate data coming from the stream.

Where as DirectoryStream is specifically designed to cater loading, filtering and iterating through file system directories in a easy to use API.

Java Stream API has clear cut common usage functions and corresponding SAM (Single Abstract Method) interfaces to ease coding for almost any usecase.

Where as DirectoryStream has convenient functions and interfaces to carry out loading, filtering, iterating over directories easy.

Upvotes: 2

Related Questions