FastCSV: High-Performance CSV Processing for Million-Row Files in Java
This tutorial introduces FastCSV, a zero-dependency Java library for high-speed CSV parsing and writing, demonstrating Maven setup, sequential and paginated reading, writer/reader configuration, bean mapping via streams, GZIP compression, and robust handling of malformed data like empty lines and field-count mismatches.
Reading font
Introduction
In daily backend development, data import/export (reports, risk-control flows, log backups) is unavoidable. CSV remains the most common exchange format due to its lightweight, universal nature. However, when business scales and operations hand over CSV files with millions of rows — hundreds of megabytes or even gigabytes — systems often hit OOM, CPU spikes, and slow responses.
This article details an open-source component: FastCSV . FastCSV is a high-performance CSV parser and writer for Java, released under the MIT license. It is designed for speed and minimal footprint while fully complying with RFC 4180. Benchmark results (shown in the article's image) demonstrate its superior throughput compared to other libraries.
Core Use Cases
Big-data applications: efficient massive data read/write
Small-data applications: lightweight library with zero extra dependencies
Key Features
Ultra-fast CSV read/write
Zero runtime dependencies
Minimal resource consumption
Null-safe, developer-friendly API
GraalVM Native Image compatible
OSGi-compliant packaging
Actively maintained
Well-tested and documented
RFC 4180 Compliance
Newlines and delimiters inside fields
Escaped quotes ("") in quoted fields
Configurable field separator
CRLF (Windows), LF (Unix), CR (classic Mac) line endings
Unicode support
System Requirements
4.x: Java ≥ 17 (Android 14 / API 34)
3.x: Java ≥ 11 (Android 13 / API 33)
2.x: Java ≥ 8 (Android 8 / API 26)
Practical Examples
2.1 Environment Setup
Add the Maven dependency (version 4.4.1 shown; choose version matching your Java version):
<dependency>
<groupId>de.siegmar</groupId>
<artifactId>fastcsv</artifactId>
<version>4.4.1</version>
</dependency>2.2 Quick Start
Writing CSV CsvWriter provides a fluent API for writing records:
Path file = Path.of("f:/output.csv");
try (CsvWriter csv = CsvWriter.builder().build(file)) {
csv
.writeRecord("1", "张三", "33")
.writeRecord("2", "李四", "22");
}Output:
1,张三,33
2,李四,22Reading CSV
FastCSV offers two main reader classes: CsvReader (sequential) and IndexedCsvReader (paginated).
Sequential Reading
Path file = Path.of("f:/output.csv");
try (CsvReader<CsvRecord> csv = CsvReader.builder().ofCsvRecord(file)) {
csv.forEach(System.out::println);
}Reading with Headers (NamedCsvRecord)
Path file = Path.of("f:/output.csv");
try (CsvReader<NamedCsvRecord> csv = CsvReader.builder().ofNamedCsvRecord(file)) {
csv.forEach(rec -> System.out.println(rec.getField("name")));
}CSV file format:
id,name,age
1,张三,33
2,李四,22Output:
张三
李四Paginated Reading with IndexedCsvReader
Reads in pages (pageSize=2 in example):
Path file = Path.of("f:/output.csv");
try (IndexedCsvReader<CsvRecord> csv = IndexedCsvReader.builder().pageSize(2).ofCsvRecord(file)) {
CsvIndex index = csv.getIndex();
int pageSize = index.pages().size();
for (int i = 0; i < pageSize; i++) {
List<CsvRecord> csvRecords = csv.readPage(i);
System.err.println(Arrays.toString(csvRecords.toArray()));
}
}Output shows three pages of two records each, with line numbers and field arrays:
[CsvRecord[startingLineNumber=1, fields=[1, 张三, 33], comment=false], CsvRecord[startingLineNumber=2, fields=[2, 李四, 25], comment=false]]
[CsvRecord[startingLineNumber=3, fields=[3, 王五, 32], comment=false], CsvRecord[startingLineNumber=4, fields=[4, 田七, 24], comment=false]]
[CsvRecord[startingLineNumber=5, fields=[5, 赵六, 66], comment=false], CsvRecord[startingLineNumber=6, fields=[6, 李丸珍, 45], comment=false]]2.3 CSV Read/Write Configuration
Builders allow flexible configuration:
// Reader
CsvReader.builder()
.fieldSeparator(';')
.quoteCharacter('"')
.commentStrategy(CommentStrategy.SKIP)
.commentCharacter('#')
.skipEmptyLines(true)
.extraFieldStrategy(FieldMismatchStrategy.STRICT)
.missingFieldStrategy(FieldMismatchStrategy.STRICT)
.allowUnclosedQuote(true)
.detectBomHeader(false)
.maxBufferSize(16777216);
// Writer
CsvWriter.builder()
.fieldSeparator(',')
.quoteCharacter('"')
.quoteStrategy(QuoteStrategies.ALWAYS)
.commentCharacter('#')
.lineDelimiter(LineDelimiter.LF);2.4 Advanced Usage
Bean Mapping
Many CSV libraries use reflection for bean mapping, incurring performance overhead contrary to FastCSV's speed goal. Leveraging Java Stream mapping, FastCSV provides similar convenience without sacrificing performance.
public static void main(String[] args) throws Exception {
Path file = Path.of("f:/output.csv");
try (CsvReader<NamedCsvRecord> csv = CsvReader.builder().ofNamedCsvRecord(file)) {
csv.stream().map(ReadCSVTest04::mapPerson).forEach(System.out::println);
}
}
static Person mapPerson(final NamedCsvRecord rec) {
return new Person(Long.parseLong(rec.getField("id")), rec.getField("name"), Integer.valueOf(rec.getField("age")));
}
record Person(long id, String name, Integer age) {}Output:
Person[id=1, name=张三, age=33]
Person[id=2, name=李四, age=25]
Person[id=3, name=王五, age=32]
Person[id=4, name=田七, age=24]
Person[id=5, name=赵六, age=66]
Person[id=6, name=李丸珍, age=45]Compressed CSV (GZIP)
Compressing CSV saves disk space and transfer time; depending on I/O performance, it can also speed up processing.
public static void main(String[] args) throws IOException {
final Path file = Files.createTempFile("fastcsv", ".csv.gz");
file.toFile().deleteOnExit();
writeCsvGzipped(file);
readCsvGzipped(file);
}
static void writeCsvGzipped(final Path file) throws IOException {
System.out.println("Writing compressed CSV file: " + file);
try (var csv = CsvWriter.builder().build(new GZIPOutputStream(Files.newOutputStream(file)))) {
csv.writeRecord("1", "张三", "33")
.writeRecord("2", "李四", "22");
}
}
static void readCsvGzipped(final Path file) throws IOException {
System.out.println("Reading compressed CSV file: " + file);
try (var csv = CsvReader.builder().ofCsvRecord(new GZIPInputStream(Files.newInputStream(file)))) {
csv.forEach(System.out::println);
}
}Handling Ambiguous Data
CSV files often contain ambiguities:
Empty lines (no data)
Empty fields (no data in a field)
Varying field counts per record
FastCSV provides strategies to handle these. Example with mismatched field counts:
public static void main(String[] args) throws Exception {
final String data = """
foo,bar
foo
foo,bar,baz
""";
try {
CsvReader.builder().ofCsvRecord(data).forEach(System.out::println);
} catch (final CsvParseException e) {
System.out.println("Exception expected due to different field counts:");
e.printStackTrace(System.out);
}
CsvReader.builder().extraFieldStrategy(FieldMismatchStrategy.IGNORE)
.missingFieldStrategy(FieldMismatchStrategy.IGNORE).ofCsvRecord(data).forEach(System.out::println);
CsvReader.builder().extraFieldStrategy(FieldMismatchStrategy.SKIP).missingFieldStrategy(FieldMismatchStrategy.SKIP)
.ofCsvRecord(data).forEach(System.out::println);
}Output demonstrates strict mode throwing exception, IGNORE mode accepting extra/missing fields, and SKIP mode discarding problematic records.
Treating Empty Fields as null
CSV standard (RFC 4180) has no null concept, but database import/export often needs to distinguish null from empty string. FastCSV's core principle is a null-free API (no public method returns null) to prevent NPEs. To represent null, a workaround using a FieldModifier is shown:
public static void main(String[] args) throws Exception {
final String data = """
firstName,middleName,lastName
John,,Doe
Jane,"",Smith
""";
final NamedCsvRecordHandler callbackHandler = NamedCsvRecordHandler
.of(builder -> builder.fieldModifier(new NullFieldModifier()));
CsvReader.builder().build(callbackHandler, data).stream().map(ReadNullFieldTest::mapPerson)
.forEach(System.out::println);
}
static Person mapPerson(final NamedCsvRecord record) {
return new Person(nullable(record.getField("firstName")), nullable(record.getField("middleName")),
nullable(record.getField("lastName")));
}
static String nullable(final String fieldValue) {
return NullFieldModifier.isNull(fieldValue) ? null : fieldValue;
}
static class NullFieldModifier implements FieldModifier {
private static final String NULL_MARKER = "NULL:" + UUID.randomUUID();
@Override
public String modify(final long startingLineNumber, final int fieldIdx, final boolean quoted, final String field) {
return !quoted && field.isEmpty() ? NULL_MARKER : field;
}
static boolean isNull(final String field) {
return NULL_MARKER.equals(field);
}
}
record Person(String firstName, String middleName, String lastName) {}Output:
Person[firstName=John, middleName=null, lastName=Doe]
Person[firstName=Jane, middleName=, lastName=Smith]Unquoted empty field becomes null; quoted empty string remains empty string.
More advanced operations: https://fastcsv.org/
For questions about attribution, corrections or content rights, please contactand we will review it promptly.
Published
AI-assisted summary