Files.newDirectoryStream vs. Files.list

后端 未结 1 1317
一生所求
一生所求 2021-02-20 11:34

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

1条回答
  •  独厮守ぢ
    2021-02-20 12:13

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

    0 讨论(0)
提交回复
热议问题