Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions src/main/java/org/apache/commons/io/FileUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -1996,7 +1996,29 @@ public static Iterator<File> iterateFiles(final File directory, final IOFileFilt
* @since 1.2
*/
public static Iterator<File> iterateFiles(final File directory, final String[] extensions, final boolean recursive) {
return Uncheck.apply(d -> streamFiles(d, recursive, extensions).iterator(), directory);
return Uncheck.apply(d -> {
Stream<File> stream = streamFiles(d, recursive, extensions);
Iterator<File> iter = stream.iterator();

// Wrap the iterator to allow closing the stream after consumption
return new Iterator<File>() {
@Override
public boolean hasNext() {
boolean ret = iter.hasNext();

if (!ret) {
stream.close();
}

return ret;
}

@Override
public File next() {
return iter.next();
}
};
}, directory);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for an anonymous class:

return StreamIterator.iterator(Uncheck.get(() -> streamFiles(directory, recursive, extensions)));

}

/**
Expand Down Expand Up @@ -2238,7 +2260,11 @@ public static Collection<File> listFiles(final File directory, final IOFileFilte
* @return a collection of java.io.File with the matching files
*/
public static Collection<File> listFiles(final File directory, final String[] extensions, final boolean recursive) {
return Uncheck.apply(d -> toList(streamFiles(d, recursive, extensions)), directory);
return Uncheck.apply(d -> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've adopted a variant of this fix in git master. You are credited in changes.xml :-)

try (Stream<File> fileStream = streamFiles(d, recursive, extensions)) {
return toList(fileStream);
}
}, directory);
}

/**
Expand Down