Skip to content

Commit aefc8f4

Browse files
committed
IO-681 IOUtils.close(Closeable) - allow a list
1 parent e040627 commit aefc8f4

3 files changed

Lines changed: 18 additions & 4 deletions

File tree

src/changes/changes.xml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,9 @@ The <action> type attribute can be add,update,fix,remove.
116116
<action dev="ggregory" type="update" due-to="Dependabot">
117117
Update spotbugs from 4.0.6 to 4.1.1 #134.
118118
</action>
119+
<action dev="sebb" type="add">
120+
IO-681 IOUtils.close(Closeable) should allow a list of closeables
121+
</action>
119122
</release>
120123
<!-- The release date is the date RC is cut -->
121124
<release version="2.7" date="2020-05-24" description="Java 8 required.">

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -367,13 +367,15 @@ public static void closeQuietly(final Closeable closeable, final Consumer<IOExce
367367
/**
368368
* Closes the given {@link Closeable} as a null-safe operation.
369369
*
370-
* @param closeable The resource to close, may be null.
370+
* @param closeables The resource(s) to close, may be null.
371371
* @throws IOException if an I/O error occurs.
372372
* @since 2.7
373373
*/
374-
public static void close(final Closeable closeable) throws IOException {
375-
if (closeable != null) {
376-
closeable.close();
374+
public static void close(final Closeable... closeables) throws IOException {
375+
for(Closeable closeable : closeables) {
376+
if (closeable != null) {
377+
closeable.close();
378+
}
377379
}
378380
}
379381

src/test/java/org/apache/commons/io/IOUtilsTestCase.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,15 @@ public void setUp() {
146146
assertThrows(IOException.class, () -> IOUtils.close(new YellOnCloseReader(new StringReader("s"))));
147147
}
148148

149+
@Test public void testCloseMulti() {
150+
Closeable nulCloseable = null;
151+
Closeable [] closeables = {null, null};
152+
assertDoesNotThrow(() -> IOUtils.close(nulCloseable,nulCloseable));
153+
assertDoesNotThrow(() -> IOUtils.close(closeables));
154+
assertDoesNotThrow(() -> IOUtils.close(new StringReader("s"),nulCloseable));
155+
assertThrows(IOException.class, () -> IOUtils.close(nulCloseable, new YellOnCloseReader(new StringReader("s"))));
156+
}
157+
149158
@Test public void testCloseConsumer() {
150159
Closeable nulCloseable = null;
151160
assertDoesNotThrow(() -> IOUtils.close(nulCloseable, null)); // null consumer

0 commit comments

Comments
 (0)