diff --git a/src/main/java/org/apache/commons/io/IOUtils.java b/src/main/java/org/apache/commons/io/IOUtils.java index 23f85b11cb3..6c2f6c9b2b2 100644 --- a/src/main/java/org/apache/commons/io/IOUtils.java +++ b/src/main/java/org/apache/commons/io/IOUtils.java @@ -747,13 +747,9 @@ public static void close(final Closeable closeable, final IOConsumer { // noop }; + /** + * Applies the given {@link IOConsumer} action to the object if the consumer is not {@code null}. Otherwise, does nothing. + * + * @param consumer the consumer to consume. + * @param object the object to be consumed. + * @param the type of the argument the consumer accepts. + * @throws IOException Thrown when the consumer fails. + * @since 2.23.0 + */ + static void accept(final IOConsumer consumer, final T object) throws IOException { + if (consumer != null) { + consumer.accept(object); + } + } + /** * Performs an action for each element of the collection gathering any exceptions. * diff --git a/src/test/java/org/apache/commons/io/function/IOConsumerTest.java b/src/test/java/org/apache/commons/io/function/IOConsumerTest.java index 172973b206f..d0aefff5c74 100644 --- a/src/test/java/org/apache/commons/io/function/IOConsumerTest.java +++ b/src/test/java/org/apache/commons/io/function/IOConsumerTest.java @@ -54,6 +54,17 @@ void testAccept() throws IOException { assertEquals("A1", ref.get()); } + @Test + void testAcceptStatic() throws IOException { + IOConsumer.accept(null, null); + IOConsumer.accept((IOConsumer) null, "."); + // + final AtomicReference ref = new AtomicReference<>(); + final IOConsumer consumer = s -> ref.set(s + "1"); + IOConsumer.accept(consumer, "A"); + assertEquals("A1", ref.get()); + } + @Test void testAndThen() throws IOException { final AtomicReference ref = new AtomicReference<>();