Skip to content

Quick Start Guide

Declare dependency

To get started with FastCSV, add the following dependency to your project:

build.gradle.kts
dependencies {
implementation("de.siegmar:fastcsv:3.3.1")
}

Write CSV

The CsvWriter class provides a fluent API to write CSV records. You’ll find all the necessary methods to write CSV records in that class.

To write some basic CSV records to a file, use the following code snippet:

Path file = Paths.get("output.csv");
try (CsvWriter csv = CsvWriter.builder().build(file)) {
csv
.writeRecord("header 1", "header 2")
.writeRecord("value 1", "value 2");
}

Read CSV

FastCSV provides two main classes to read CSV records: CsvReader and IndexedCsvReader.

Reading CSV records sequentially

The regular CsvReader reads CSV records sequentially. To iterate over CSV records in a file and print them to the console, use the following code snippet:

Path file = Paths.get("input.csv");
try (CsvReader<CsvRecord> csv = CsvReader.builder().ofCsvRecord(file)) {
csv.forEach(System.out::println);
}

The CsvReader also provides a method for reading CSV files with headers:

Path file = Paths.get("input.csv");
try (CsvReader<NamedCsvRecord> csv = CsvReader.builder().ofNamedCsvRecord(file)) {
csv.forEach(rec -> System.out.println(rec.getField("foo")));
}

Both methods (ofCsvRecord and ofNamedCsvRecord) are overloaded for other input sources like Reader and String. Using the more generic build method, you can also make use of the Callback mechanism to process the records. See Custom callback handler example for more information.

Reading CSV records in pages

The IndexedCsvReader on the other hand, reads CSV records in pages. This is useful, for example, when you have a user interface and want to display only a subset of the records at a time and allow the user to navigate through the records.

The following code snippet demonstrates how to read the last page of a CSV file:

Path file = Paths.get("input.csv");
try (IndexedCsvReader<CsvRecord> csv = IndexedCsvReader.builder().pageSize(10).ofCsvRecord(file)) {
CsvIndex index = csv.getIndex();
int lastPage = index.getPageCount() - 1;
List<CsvRecord> csvRecords = csv.readPage(lastPage);
}

More details on the IndexedCsvReader can be found in the Indexed reading example.