Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Files.newDirectoryStream vs. Files.list

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?

like image 473
Sebastian S Avatar asked Nov 12 '15 10:11

Sebastian S


1 Answers

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

like image 68
Tagir Valeev Avatar answered Nov 08 '22 19:11

Tagir Valeev