Files.newDirectoryStream与Files.list [英] Files.newDirectoryStream vs. Files.list

查看:492
本文介绍了Files.newDirectoryStream与Files.list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Files.list(Path)使用 Files.newDirectoryStream(路径)内部和基本上只是包裹DirectoryStream。

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


  1. 但我不明白,当我想使用第一个或后一个时。

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

如果我想使用流API,这只是一种方便的方法吗?我自己可以做到这一点相当容易,看到这个问题

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.

如果查看 Files.list 的实现,内部DirectoryStream抛出的异常包含在 UncheckedIOException 中。我应该知道的任何事情吗?

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. 这通常是一种风格问题。如果要使用外部迭代( for(Path path:dirStream)),请使用 newDirectoryStream 。如果您想利用Stream API操作(例如 map filter 已排序等),改为使用 list

  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.

区别在于异常处理。在 Files.list 遍历期间发生的任何异常都从 DirectoryIteratorException 转换为 UncheckedIOException 。另一个细微差别是spliterator明确报告 DISTINCT 特征,所以如果你做 Files.list()。distinct() distinct()步骤将被优化(因为已经知道元素是不同的)。使用 Iterable.spliterator()默认实现时,不会执行此优化。

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.

这里没什么特别的。您可能希望在终端流操作执行过程中弹出 UncheckedIOException (例如,由于访问网络文件夹时网络超时)。

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

这篇关于Files.newDirectoryStream与Files.list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆