Add and reuse org.apache.commons.io.IOUtils.close(Closeable,
Consumer<IOException>)
MODIFY
src/changes/changes.xml
src/changes/changes.xml
@@ -161,6 +161,9 @@ The <action> type attribute can be add,update,fix,remove.
<action issue="IO-635" dev="ggregory" type="add" due-to="Gary Gregory">
Add org.apache.commons.io.IOUtils.close(Closeable).
</action>
+ <action issue="IO-636" dev="ggregory" type="add" due-to="Gary Gregory">
+ Add and reuse org.apache.commons.io.IOUtils.close(Closeable, Consumer&lt;IOException&gt;)
+ </action>
</release>
<release version="2.6" date="2017-10-15" description="Java 7 required, Java 9 supported.">

MODIFY
src/main/java/org/apache/commons/io/FileUtils.java
src/main/java/org/apache/commons/io/FileUtils.java
@@ -1847,12 +1847,7 @@ public static LineIterator lineIterator(final File file, final String encoding)
inputStream = openInputStream(file);
return IOUtils.lineIterator(inputStream, encoding);
} catch (final IOException | RuntimeException ex) {
- try {
- IOUtils.close(inputStream);
- }
- catch (final IOException e) {
- ex.addSuppressed(e);
- }
+ IOUtils.close(inputStream, e -> ex.addSuppressed(e));
throw ex;
}
}

MODIFY
src/main/java/org/apache/commons/io/IOUtils.java
src/main/java/org/apache/commons/io/IOUtils.java
import java.util.Collection;
import java.util.List;
import java.util.Objects;
+import java.util.function.Consumer;
import org.apache.commons.io.output.AppendableWriter;
import org.apache.commons.io.output.ByteArrayOutputStream;
@@ -342,11 +343,7 @@ public static BufferedWriter buffer(final Writer writer, final int size) {
*/
@Deprecated
public static void closeQuietly(final Closeable closeable) {
- try {
- close(closeable);
- } catch (final IOException ioe) {
- // ignore
- }
+ close(closeable, null);
}
/**
@@ -362,6 +359,25 @@ public static void close(final Closeable closeable) throws IOException {
}
}
+ /**
+ * Closes the given {@link Closeable} as a null-safe operation.
+ *
+ * @param closeable The resource to close, may be null.
+ * @param consumer Consume the IOException thrown by {@link Closeable#close()}.
+ * @since 2.7
+ */
+ public static void close(final Closeable closeable, final Consumer<IOException> consumer) {
+ if (closeable != null) {
+ try {
+ closeable.close();
+ } catch (IOException e) {
+ if (consumer != null) {
+ consumer.accept(e);
+ }
+ }
+ }
+ }
+
/**
* Closes a URLConnection.
*

MODIFY
src/main/java/org/apache/commons/io/LineIterator.java
src/main/java/org/apache/commons/io/LineIterator.java
@@ -103,11 +103,7 @@ public boolean hasNext() {
}
}
} catch(final IOException ioe) {
- try {
- close();
- } catch (final IOException e) {
- ioe.addSuppressed(e);
- }
+ IOUtils.close(this, e -> ioe.addSuppressed(e));
throw new IllegalStateException(ioe);
}
}

[IO-636] Add and reuse org.apache.commons.io.IOUtils.close(Closeable,
Consumer<IOException>)