Skip to content

Commit 95847a1

Browse files
committed
IOUtils chain together IOException for multiple Closeable instances, add overload
1 parent bc80b9a commit 95847a1

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

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

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -392,8 +392,19 @@ public static void close(final Closeable closeable) throws IOException {
392392
*/
393393
public static void close(final Closeable... closeables) throws IOException {
394394
if (closeables != null) {
395+
IOException ioexception = null;
395396
for (final Closeable closeable : closeables) {
396-
close(closeable);
397+
try {
398+
close(closeable);
399+
} catch (IOException ex) {
400+
if (ioexception == null) {
401+
ioexception = new IOException("IOUtils.close failed");
402+
}
403+
ioexception.addSuppressed(ex);
404+
}
405+
}
406+
if (ioexception != null) {
407+
throw ioexception;
397408
}
398409
}
399410
}
@@ -418,6 +429,25 @@ public static void close(final Closeable closeable, final IOConsumer<IOException
418429
}
419430
}
420431

432+
/**
433+
* Closes the given {@link Closeable} as a null-safe operation.
434+
*
435+
* @param closeable The resource(s) to close, may be null.
436+
* @param consumer Consume the IOException thrown by {@link Closeable#close()}.
437+
* @throws IOException if an I/O error occurs.
438+
*/
439+
public static void close(final Closeable[] closeables, final IOConsumer<IOException> consumer) throws IOException {
440+
if (closeables != null) {
441+
try {
442+
close(closeables);
443+
} catch (final IOException e) {
444+
if (consumer != null) {
445+
consumer.accept(e);
446+
}
447+
}
448+
}
449+
}
450+
421451
/**
422452
* Closes a URLConnection.
423453
*

0 commit comments

Comments
 (0)