diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 6958cfe15..dcc47ff66 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -83,6 +83,7 @@
Add missing @Test to CSVFormatTest.testEqualsSkipHeaderRecord#testEqualsSkipHeaderRecord() (#639).
Fix Predefined @see references in CSVFormat (#641).
Document CSVFormat validation exceptions.
+ Close the file writer if CSVPrinter construction fails.
Add an "Android Compatibility" section to the web site.
Add CSVParser.Builder.setByteOffset(long) (#604).
diff --git a/src/main/java/org/apache/commons/csv/CSVFormat.java b/src/main/java/org/apache/commons/csv/CSVFormat.java
index 43c8abcb6..f1b2f3f0f 100644
--- a/src/main/java/org/apache/commons/csv/CSVFormat.java
+++ b/src/main/java/org/apache/commons/csv/CSVFormat.java
@@ -2720,7 +2720,29 @@ private void print(final Object object, final CharSequence value, final Appendab
*/
@SuppressWarnings("resource")
public CSVPrinter print(final Path out, final Charset charset) throws IOException {
- return print(Files.newBufferedWriter(out, charset));
+ return printWithOwnedWriter(Files.newBufferedWriter(out, charset));
+ }
+
+ /**
+ * Creates a printer for a writer opened by the path overload, closing the writer if construction fails.
+ *
+ * @param out The writer to pass to the printer.
+ * @return A printer to the writer.
+ * @throws IOException If the optional header comments or header cannot be printed.
+ */
+ CSVPrinter printWithOwnedWriter(final Writer out) throws IOException {
+ try {
+ return print(out);
+ } catch (final IOException | RuntimeException | Error creationFailure) {
+ try {
+ out.close();
+ } catch (final IOException | RuntimeException | Error closeFailure) {
+ if (closeFailure != creationFailure) {
+ creationFailure.addSuppressed(closeFailure);
+ }
+ }
+ throw creationFailure;
+ }
}
/**
diff --git a/src/test/java/org/apache/commons/csv/CSVFormatTest.java b/src/test/java/org/apache/commons/csv/CSVFormatTest.java
index 14067d13c..7256201a5 100644
--- a/src/test/java/org/apache/commons/csv/CSVFormatTest.java
+++ b/src/test/java/org/apache/commons/csv/CSVFormatTest.java
@@ -30,6 +30,7 @@
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -43,6 +44,7 @@
import java.io.ObjectOutputStream;
import java.io.Reader;
import java.io.StringReader;
+import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
@@ -56,6 +58,8 @@
import org.apache.commons.csv.CSVFormat.Builder;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
/**
* Tests {@link CSVFormat}.
@@ -70,6 +74,38 @@ public enum Header {
Name, Email, Phone
}
+ private static final class RecordingWriter extends Writer {
+
+ private final IOException writeFailure;
+ private final IOException closeFailure;
+ private int closeCount;
+
+ RecordingWriter(final IOException writeFailure, final IOException closeFailure) {
+ this.writeFailure = writeFailure;
+ this.closeFailure = closeFailure;
+ }
+
+ @Override
+ public void close() throws IOException {
+ closeCount++;
+ if (closeFailure != null) {
+ throw closeFailure;
+ }
+ }
+
+ @Override
+ public void flush() {
+ // no-op
+ }
+
+ @Override
+ public void write(final char[] buffer, final int offset, final int length) throws IOException {
+ if (writeFailure != null) {
+ throw writeFailure;
+ }
+ }
+ }
+
private static void assertNotEqualsFlip(final Object right, final Object left) {
assertNotEquals(right, left);
assertNotEquals(left, right);
@@ -912,6 +948,38 @@ void testNullRecordSeparatorCsv106__Deprecated() {
assertFalse(formatStr.endsWith("null"));
}
+ @Test
+ void testPrintBorrowedWriterLeavesOwnershipOnConstructionFailure() {
+ final CSVFormat format = CSVFormat.DEFAULT.builder().setHeader("A").get();
+ final IOException writeFailure = new IOException("header write failed");
+ final RecordingWriter writer = new RecordingWriter(writeFailure, null);
+ assertSame(writeFailure, assertThrows(IOException.class, () -> format.print(writer)));
+ assertEquals(0, writer.closeCount);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testPrintOwnedWriterClosesAfterHeaderFailure(final boolean sameFailure) {
+ final CSVFormat format = CSVFormat.DEFAULT.builder().setHeader("A").get();
+ final IOException writeFailure = new IOException("header write failed");
+ final IOException closeFailure = sameFailure ? writeFailure : new IOException("close failed");
+ final RecordingWriter writer = new RecordingWriter(writeFailure, closeFailure);
+ final IOException actual = assertThrows(IOException.class, () -> format.printWithOwnedWriter(writer));
+ assertSame(writeFailure, actual);
+ assertEquals(1, writer.closeCount);
+ assertArrayEquals(sameFailure ? new Throwable[0] : new Throwable[] {closeFailure}, actual.getSuppressed());
+ }
+
+ @Test
+ void testPrintOwnedWriterTransfersOwnershipOnSuccess() throws IOException {
+ final RecordingWriter writer = new RecordingWriter(null, null);
+ try (CSVPrinter printer = CSVFormat.DEFAULT.printWithOwnedWriter(writer)) {
+ printer.printRecord("value");
+ assertEquals(0, writer.closeCount);
+ }
+ assertEquals(1, writer.closeCount);
+ }
+
@Test
void testPrintRecord() throws IOException {
final Appendable out = new StringBuilder();