Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions src/main/java/org/apache/commons/io/IOUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -747,13 +747,9 @@ public static void close(final Closeable closeable, final IOConsumer<IOException
try {
closeable.close();
} catch (final IOException e) {
if (consumer != null) {
consumer.accept(e);
}
IOConsumer.accept(consumer, e);
} catch (final Exception e) {
if (consumer != null) {
consumer.accept(new IOException(e));
}
IOConsumer.accept(consumer, new IOException(e));
}
}
}
Expand Down
15 changes: 15 additions & 0 deletions src/main/java/org/apache/commons/io/function/IOConsumer.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,21 @@ public interface IOConsumer<T> {
// 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 <T> the type of the argument the consumer accepts.
* @throws IOException Thrown when the consumer fails.
* @since 2.23.0
*/
static <T> void accept(final IOConsumer<T> consumer, final T object) throws IOException {
if (consumer != null) {
consumer.accept(object);
}
}

/**
* Performs an action for each element of the collection gathering any exceptions.
*
Expand Down
11 changes: 11 additions & 0 deletions src/test/java/org/apache/commons/io/function/IOConsumerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,17 @@ void testAccept() throws IOException {
assertEquals("A1", ref.get());
}

@Test
void testAcceptStatic() throws IOException {
IOConsumer.accept(null, null);
IOConsumer.accept((IOConsumer<String>) null, ".");
//
final AtomicReference<String> ref = new AtomicReference<>();
final IOConsumer<String> consumer = s -> ref.set(s + "1");
IOConsumer.accept(consumer, "A");
assertEquals("A1", ref.get());
}

@Test
void testAndThen() throws IOException {
final AtomicReference<String> ref = new AtomicReference<>();
Expand Down
Loading