How to make a Stream from a DirectoryStream
While it is possible to convert a DirectoryStream
into a Stream
using its spliterator
method, there is no reason to do so. Just create a Stream<Path>
in the first place.
E.g., instead of calling Files.newDirectoryStream(Path)
just call Files.list(Path)
.
The overload of newDirectoryStream
which accepts an additional Filter
may be replaced by Files.list(Path).filter(Predicate)
and there are additional operations like Files.find
and Files.walk
returning a Stream<Path>
, however, I did not find a replacement for the case you want to use the “glob pattern”. That seems to be the only case where translating a DirectoryStream
into a Stream
might be useful (I prefer using regular expressions anyway)…
DirectoryStream
is not a Stream
(it's been there since Java 7, before the streams api was introduced in Java 8) but it implements the Iterable<Path>
interface so you could write:
try (DirectoryStream<Path> ds = ...) {
Stream<Path> s = StreamSupport.stream(ds.spliterator(), false);
}
DirectoryStream
has a method that returns a spliterator. So just do:
Stream<Path> stream = StreamSupport.stream(myDirectoryStream.spliterator(), false);
You might want to see this question, which is basically what your problem reduces to: How to create a Stream from an Iterable.