Skip to content

Commit 2c143a2

Browse files
authored
Add IOConsumer.accept(IOConsumer, T) (#846)
1 parent 83fdee1 commit 2c143a2

3 files changed

Lines changed: 28 additions & 6 deletions

File tree

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

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -747,13 +747,9 @@ public static void close(final Closeable closeable, final IOConsumer<IOException
747747
try {
748748
closeable.close();
749749
} catch (final IOException e) {
750-
if (consumer != null) {
751-
consumer.accept(e);
752-
}
750+
IOConsumer.accept(consumer, e);
753751
} catch (final Exception e) {
754-
if (consumer != null) {
755-
consumer.accept(new IOException(e));
756-
}
752+
IOConsumer.accept(consumer, new IOException(e));
757753
}
758754
}
759755
}

src/main/java/org/apache/commons/io/function/IOConsumer.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,21 @@ public interface IOConsumer<T> {
4242
// noop
4343
};
4444

45+
/**
46+
* Applies the given {@link IOConsumer} action to the object if the consumer is not {@code null}. Otherwise, does nothing.
47+
*
48+
* @param consumer the consumer to consume.
49+
* @param object the object to be consumed.
50+
* @param <T> the type of the argument the consumer accepts.
51+
* @throws IOException Thrown when the consumer fails.
52+
* @since 2.23.0
53+
*/
54+
static <T> void accept(final IOConsumer<T> consumer, final T object) throws IOException {
55+
if (consumer != null) {
56+
consumer.accept(object);
57+
}
58+
}
59+
4560
/**
4661
* Performs an action for each element of the collection gathering any exceptions.
4762
*

src/test/java/org/apache/commons/io/function/IOConsumerTest.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,17 @@ void testAccept() throws IOException {
5454
assertEquals("A1", ref.get());
5555
}
5656

57+
@Test
58+
void testAcceptStatic() throws IOException {
59+
IOConsumer.accept(null, null);
60+
IOConsumer.accept((IOConsumer<String>) null, ".");
61+
//
62+
final AtomicReference<String> ref = new AtomicReference<>();
63+
final IOConsumer<String> consumer = s -> ref.set(s + "1");
64+
IOConsumer.accept(consumer, "A");
65+
assertEquals("A1", ref.get());
66+
}
67+
5768
@Test
5869
void testAndThen() throws IOException {
5970
final AtomicReference<String> ref = new AtomicReference<>();

0 commit comments

Comments
 (0)