Skip to content

Commit 893935e

Browse files
committed
[IO-811] StreamIterator fails to close its internal Stream
Test PR coming next
1 parent 3799e50 commit 893935e

2 files changed

Lines changed: 11 additions & 2 deletions

File tree

src/changes/changes.xml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ The <action> type attribute can be add,update,fix,remove.
6363
<action dev="ggregory" type="fix" issue="IO-811" due-to="Adam Rauch, Gary Gregory">
6464
FileUtils.iterateFiles(File, String[], boolean) fails to close its internal Stream.
6565
</action>
66+
<action dev="ggregory" type="fix" issue="IO-811" due-to="Adam Rauch, Gary Gregory">
67+
StreamIterator fails to close its internal Stream.
68+
</action>
6669
</release>
6770
<release version="2.14.0" date="2023-09-24" description="Java 8 is required.">
6871
<!-- FIX -->

src/main/java/org/apache/commons/io/StreamIterator.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,15 +45,16 @@ final class StreamIterator<E> implements Iterator<E>, Closeable {
4545
* @param stream The stream iterate.
4646
* @return A new iterator.
4747
*/
48-
@SuppressWarnings("resource") // Caller MUST close or iterate to the end.
4948
public static <T> Iterator<T> iterator(final Stream<T> stream) {
50-
return new StreamIterator<>(stream).iterator;
49+
return new StreamIterator<>(stream);
5150
}
5251

5352
private final Iterator<E> iterator;
5453

5554
private final Stream<E> stream;
5655

56+
private boolean closed;
57+
5758
private StreamIterator(final Stream<E> stream) {
5859
this.stream = Objects.requireNonNull(stream, "stream");
5960
this.iterator = stream.iterator();
@@ -64,11 +65,16 @@ private StreamIterator(final Stream<E> stream) {
6465
*/
6566
@Override
6667
public void close() {
68+
closed = true;
6769
stream.close();
6870
}
6971

7072
@Override
7173
public boolean hasNext() {
74+
if (closed) {
75+
// Calling Iterator#hasNext() on a closed java.nio.file.FileTreeIterator causes an IllegalStateException.
76+
return false;
77+
}
7278
final boolean hasNext = iterator.hasNext();
7379
if (!hasNext) {
7480
close();

0 commit comments

Comments
 (0)