Files.newDirectoryStream vs File.listFiles
Alan Bateman
Alan.Bateman at oracle.com
Sun May 20 08:46:32 PDT 2012
On 19/05/2012 16:05, Paulo Levi wrote:
> The new io api seems a little verbose to me (especially the static
> methods in Files - that i assume are going to be extension methods?)
>
> I was just changing my code to use Paths instead of Files and i came
> upon this case where the the listfiles alternative seems to mandate
> laziness and one-off iteration. I get that it's good policy, however
> to retrofit code that uses eager [] iteration it won't be a smooth
> transition.
>
> Might you add a method that "drains" a hidden watch service into a
> list of paths?
The motivation for using an Iterable was to make it scalable when
working with large directories and also to smooth out the access to
remote file systems. However I accept there are other cases where you
just want to get the list of the entries via a single method and maybe
we should add a method for this. In the mean time then you can do it
yourself with:
static List<Path> listFiles(Path dir) throws IOException {
List<Path> result = new ArrayList<>();
try (DirectoryStream<Path> stream =
Files.newDirectoryStream(dir)) {
for (Path entry: stream) {
result.add(entry);
}
} catch (DirectoryIteratorException ex) {
throw ex.getCause();
}
return result;
}
and use toArray on the result if you really need it as an array.
I didn't quite get the suggestion about a "drain" method.
-Alan
More information about the nio-discuss
mailing list