This section covers the most basic usage of FastCSV. It provides examples for reading and writing CSV data.
For more advanced features, see the dedicated Examples section.
CsvReader examples
Iterative reading of some CSV data from a string
CsvReader . builder () . ofCsvRecord ( " foo1,bar1 \n foo2,bar2 " )
. forEach ( System . out :: println ) ;
Iterative reading of a CSV file
try ( CsvReader < CsvRecord > csv = CsvReader . builder () . ofCsvRecord ( file ) ) {
csv . forEach ( System . out :: println ) ;
CsvReader . builder () . ofNamedCsvRecord ( " header 1,header 2 \n field 1,field 2 " )
. forEach ( rec -> System . out . println ( rec . getField ( " header 2 " ))) ;
CsvCallbackHandler < NamedCsvRecord > callbackHandler =
new NamedCsvRecordHandler ( " header 1 " , " header 2 " ) ;
CsvReader . builder () . build ( callbackHandler, " field 1,field 2 " )
. forEach ( rec -> System . out . println ( rec . getField ( " header 2 " ))) ;
Custom settings
. commentStrategy ( CommentStrategy . SKIP )
. ignoreDifferentFieldCount ( false )
. acceptCharsAfterQuotes ( false )
IndexedCsvReader examples
Indexed reading of a CSV file
try ( IndexedCsvReader < CsvRecord > csv = IndexedCsvReader . builder () . ofCsvRecord ( file ) ) {
CsvIndex index = csv . getIndex () ;
System . out . println ( " Items of last page: " ) ;
int lastPage = index . getPageCount () - 1 ;
List < CsvRecord > csvRecords = csv . readPage ( lastPage ) ;
csvRecords . forEach ( System . out :: println ) ;
CsvWriter examples
Iterative writing of some data to a writer
var sw = new StringWriter () ;
CsvWriter . builder () . build ( sw )
. writeRecord ( " header 1 " , " header 2 " )
. writeRecord ( " value 1 " , " value 2 " ) ;
Iterative writing of a CSV file
try ( CsvWriter csv = CsvWriter . builder () . build ( file ) ) {
. writeRecord ( " header 1 " , " header 2 " )
. writeRecord ( " value 1 " , " value 2 " ) ;
Custom settings
. quoteStrategy ( QuoteStrategies . ALWAYS )
. lineDelimiter ( LineDelimiter . LF ) ;