25

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?

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Thirler
  • 20,239
  • 14
  • 63
  • 92

3 Answers3

42

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

Holger
  • 285,553
  • 42
  • 434
  • 765
  • @OlivierCailloux [`Files.list(Path)`](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#list-java.nio.file.Path-) returns a `Stream`. It does *not* build a list in memory. The same applies to `find` and `walk`. None of these methods will build a list in memory. – Holger Aug 07 '19 at 06:51
  • You are right, @Holger. As the Javadoc (that I should have read before posting) says: “The returned stream encapsulates a DirectoryStream”. So the advantages will indeed be the same. I deleted my incorrect comment. – Olivier Cailloux Aug 08 '19 at 08:26
17

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);
}
assylias
  • 321,522
  • 82
  • 660
  • 783
  • 7
    Note that `List` existed before streams as well, yet they did add `asStream()` to that ;) – Thirler Mar 02 '15 at 13:02
  • 2
    Note @Holger's answer below - you can avoid converting if you get a stream directly with `Files.newDirectoryStream(Path)`. – Andy Thomas Jun 23 '16 at 16:53
2

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.

Community
  • 1
  • 1
Alexis C.
  • 91,686
  • 21
  • 171
  • 177