Files.newDirectoryStream vs. Files.list

丶灬走出姿态 提交于 2019-12-09 16:40:49

问题


I am aware that Files.list(Path) uses Files.newDirectoryStream(Path) internally and basically just wraps the DirectoryStream.

  1. However I don't understand, when I want to use the first or the latter one.

  2. Is this just a convenience method, if I want to use the streaming API? I could have done this fairly easy myself, see this question.

  3. If one looks at the implementation of Files.list, exceptions thrown by the internal DirectoryStream are wrapped in UncheckedIOException. Anything I should know about this?


回答1:


  1. This is in general a matter of style. If you want to use external iteration (for(Path path : dirStream)) use newDirectoryStream. If you want to take the advantage of Stream API operations (like map, filter, sorted, etc.), use list instead.

  2. The difference is the exception handling. Any exceptions occurred during the Files.list traversal are converted from DirectoryIteratorException to UncheckedIOException. Another minor difference is that the spliterator explicitly reports the DISTINCT characteristic, so if you do Files.list().distinct(), the distinct() step will be optimized out (as it's already known that the elements are distinct). This optimization will not be performed when using Iterable.spliterator() default implementation.

  3. Nothing special here. You should expect that UncheckedIOException may pop in the middle of terminal stream operation execution (for example, due to network timeout when accessing the network folder).



来源:https://stackoverflow.com/questions/33668859/files-newdirectorystream-vs-files-list

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