问题
I am aware that Files.list(Path) uses Files.newDirectoryStream(Path) internally and basically just wraps the DirectoryStream.
However I don't understand, when I want to use the first or the latter one.
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.
If one looks at the implementation of
Files.list
, exceptions thrown by the internal DirectoryStream are wrapped inUncheckedIOException
. Anything I should know about this?
回答1:
This is in general a matter of style. If you want to use external iteration (
for(Path path : dirStream)
) usenewDirectoryStream
. If you want to take the advantage of Stream API operations (likemap
,filter
,sorted
, etc.), uselist
instead.The difference is the exception handling. Any exceptions occurred during the
Files.list
traversal are converted fromDirectoryIteratorException
toUncheckedIOException
. Another minor difference is that the spliterator explicitly reports theDISTINCT
characteristic, so if you doFiles.list().distinct()
, thedistinct()
step will be optimized out (as it's already known that the elements are distinct). This optimization will not be performed when usingIterable.spliterator()
default implementation.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