When reading the API for DirectoryStream
I miss a lot of functions. First of all it suggests using a for loop to go from stream to List
. And I miss the fact that it a DirectoryStream
is not a Stream
.
How can I make a Stream<Path>
from a DirectoryStream
in Java 8?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With