How to make a Stream from a DirectoryStream

久未见 提交于 2019-12-04 15:47:15

问题


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?


回答1:


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);
}



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/28806416/how-to-make-a-stream-from-a-directorystream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!