Skip to content

Fix CSV-331: CSVFormat ignores trim when printing a Reader value - #642

Open
Inf1mum wants to merge 1 commit into
apache:masterfrom
Inf1mum:fix/CSV-331-trim-reader
Open

Inf1mum wants to merge 1 commit into
apache:masterfrom
Inf1mum:fix/CSV-331-trim-reader

Conversation

@Inf1mum

@Inf1mum Inf1mum commented Nov 4, 2026

Copy link
Copy Markdown

Fixes CSV-331 — CSVFormat ignores trim when printing a Reader value.

Problem

The Javadoc of CSVFormat.print(Object, Appendable, boolean) promises that the value is trimmed when getTrim() is true, but a Reader value took an early-return branch into the streaming print(Reader, ...) path, which cannot apply trim(CharSequence). As a result, a Reader value was printed untrimmed:

final StringBuilder out = new StringBuilder();
CSVFormat.ORACLE.print(new StringReader("  Alice  "), out, true);
// expected "Alice", got "  Alice  "

Change

In print(Object, Appendable, boolean), when the value is a Reader and trimming is enabled, the reader is fully read into memory (IOUtils.toString(Reader)) and the value then goes through the regular CharSequence path where the existing trim(CharSequence) helper and quoting/escaping logic apply. When trimming is disabled, the behavior is unchanged: the value is streamed as before without holding it in memory.

  • The reader is never closed by the fix — closing remains the caller's responsibility.
  • Javadoc of print(Object, Appendable, boolean) now documents the in-memory buffering when trim is true, and the private print(Reader, ...) documents that trimming is handled by the caller.

Testing

  • Added testTrimReaderValue (includes the CSV-331 reproduction with CSVFormat.ORACLE), testTrimReaderValueWithQuotes (a trimmed Reader value that needs encapsulation is still quoted correctly), and testNoTrimReaderValue (streaming path unchanged without trim).
  • All three new tests failed before the fix and pass after it.
  • CSVFormatTest and CSVPrinterTest: 287 tests, 0 failures.

Note: when trim is true a Reader value is buffered fully in memory (documented in the Javadoc). This keeps the memory-free streaming guarantee only for the untrimmed case, matching what is possible without changing the streaming printWithQuotes(Reader)/printWithEscapes(Reader) implementations.

Signed-off-by: Inf1mum <vadim.lazuk@mail.ru>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant