Fixed size buffer Writer implementation for use with FastCSV #117
Closed
javafanboy
started this conversation in
Show and tell
Replies: 1 comment
-
The mentioned issue is found at #115 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Not sure if anybody else have the same need as I had to write as much CSV data as will fit to a fixed size byte buffer - I needed this to create messages for various cloud services that have one or more size increments for sent message (and charge you the same irrespective of how much data you actually send up to that limit).
The design I went for was to create a custom "transactional" Writer implementation that uses a fixed size buffer supporting mark/restore (to remove the effect of some incomplete write operations).
Using it I, before each call to CsvWriter.writeRecord I perform a mark (very inexpensive) and then keep inserting record after record until the buffer is full (this throws an exception that CsvWriter will re-throw as UncheckedIoException) and I then performs a "reset", send the content of the buffer as it was before the failing call to writeRecord, rewind the writer and start writing more CSV data.
An example of how adding a CSV record to this special writer can look like this:
I have observed an unexpected behavior of CsvWriter that when an exception is thrown by the underlying Writer keeps the data that failed to be written and outputs this with the next writeRecord call, in my case resulting in a duplicate, that I work-around by re-creating the CswWriter each time the exception is thrown (the buffer is full).
Assuming writeRecord always buffers all produced characters internally and only performs ONE call to the underlying Writer I could actually skip the use of mark/reset as the ByteBuffer will throw the exception before updating the data but I was not 100% sure of this and wanted a "future" proof solution that would also work with other data than that from FastCSV.
The code for this writer I created (that largely builds on standard JDK library classes like ByteBuffer and CharsetEncoder) is provided below under MIT License without any responsibility for its correctness, usability etc. - feel free to use it if you need it or if you spot any errors or improvement proposals please comment!
Beta Was this translation helpful? Give feedback.
All reactions