FastBufferedWriter.flush() does not flush the underlying Writer
Closed this issue · 2 comments
Describe the bug
When using the internally buffered writer, there is no way to flush the underlying Writer. It initially appears this should work, as the when supplying your own Writer, the flushWriter
flag is true, which causes the Writer.flush()
to be called when a record is completed; but for FastBufferedWriter, only the internal buffer gets flushed, the underlying Writer is never actually flushed:
@Override
public void flush() throws IOException {
writer.write(buf, 0, pos);
pos = 0;
}
Arguably you don't want to flush the underlying buffer after each record, but if that's the case, it certainly would be helpful to allow the caller to control when the writer is flushed. Presently the only way to flush the underlying Writer is to close it.
To Reproduce
JUnit test to reproduce the behavior:
@Test
void testFlush() throws Exception {
CsvWriter csvWriter = CsvWriter.builder().build(new OutputStreamWriter(System.out, "UTF-8"));
csvWriter.writeRecord("one", "two", "three");
// Nothing happens until CsvWriter.close() is called
}
Additional context
I suppose its atypical to use System.out as the target of CsvWriter, but I do find that useful, particularly when utilities are being developed I prefer to look at output on the console rather than writing into a file.
I don't see where this is a bug.
If you want to use your own writer for whatever reason, just call flush()
on that one if you want it to flush. The CsvWriter already sent all the data to it.
OutputStreamWriter writer = new OutputStreamWriter(System.out, "UTF-8");
CsvWriter csvWriter = CsvWriter.builder().build(writer);
csvWriter.writeRecord("one", "two", "three");
writer.flush();
Certainly this can be worked around with relatively little effort. I reported as a bug as it goes against the typical pattern for wrapping Writers. For example, all wrappers in standard library flush the wrapped writer/stream:
- java.io.BufferedWriter
- java.io.FilterWriter
- java.io.OutputStreamWriter (flushes StreamEncoder)
- java.io.PrinterWriter
- etc.
This remains true for any other I/O wrappers I can remember dealing with in other libraries.
The behavoiur here caught me by surprise as it goes against the rest of the Java ecosystem.