Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Stream from a DirectoryStream

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?

like image 695
Thirler Avatar asked Mar 02 '15 09:03

Thirler


3 Answers

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)…

like image 106
Holger Avatar answered Oct 31 '22 19:10

Holger


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);
}
like image 17
assylias Avatar answered Oct 31 '22 19:10

assylias


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.

like image 2
Alexis C. Avatar answered Oct 31 '22 21:10

Alexis C.