Java Tutorial: Read and Write Using Apache Commons CSV

CSV (Comma-Separated Values) files are widely used for storing tabular data. CSV is a simple and efficient format, whether you’re dealing with analytics, data migration, or automation scripts. In this tutorial, you’ll learn how to read from and write to CSV files in Java using the Apache Commons CSV library. Apache Commons CSV simplifies CSV file operations with a clean, robust API.

Why Use Apache Commons CSV?

Before diving into code, let’s briefly discuss why Apache Commons CSV is a solid choice for handling CSV in Java:

  • Simple API: Easy to learn and use.
  • Support for various CSV dialects: Supports RFC4180, Excel, MySQL, and more.
  • Reliable parsing and escaping: Handles edge cases like embedded commas or quotes.
  • Open-source and actively maintained.

Let’s explore how to read and write CSV files using this library.

1. Setting Up Apache Commons CSV

To use the library, add the following dependency to your project:

Maven

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-csv -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.14.0</version>
</dependency>

2. Writing to a CSV File

Let’s write a CSV file containing basic user data: ID, Name, and Email.

Example Code

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.FileWriter;
import java.io.IOException;


public class CSVWriterExample {
    public static void main(String[] args) {
        String[] headers = {"ID", "Name", "Email"};
        String filePath = "users.csv";
        try (

                FileWriter writer = new FileWriter(filePath);
                CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.builder().setHeader(headers).get())
        ) {
            csvPrinter.printRecord("1", "Alice Johnson", "alice@example.com");
            csvPrinter.printRecord("2", "Bob Smith", "bob@example.com");
            csvPrinter.printRecord("3", "Carol White", "carol@example.com");

            csvPrinter.flush();
            System.out.println("CSV file written successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Breakdown

  • CSVFormat.DEFAULT.builder().setHeader(headers).get()Sets the column headers.
  • printRecord(...)Writes individual rows.
  • flush()Ensures all data is written before closing the stream.

This code produces a well-formatted users.csv file in your working directory.

Modern CSV

Modern CSV is a powerful, user-friendly CSV editor designed for professionals who work with large datasets. It offers lightning-fast performance, intuitive navigation, and advanced features like multi-cell editing, filtering, and regex-based find and replace. You can open multi-gigabyte files effortlessly and customize nearly every aspect of your workflow. Modern CSV supports Windows, macOS, and Linux, making it accessible across platforms. Its clean interface reduces clutter and enhances productivity. With undo/redo capabilities, customizable keyboard shortcuts, and support for delimiter variations, Modern CSV empowers users to manipulate complex data efficiently. It’s ideal for developers, data analysts, and power users.

Modern CSV

3. Reading from a CSV File

Now, let’s read the data back from users.csv.

ID,Name,Email
1,Alice Johnson,alice@example.com
2,Bob Smith,bob@example.com
3,Carol White,carol@example.com

Example Reading CSV by column header

public class CSVReaderExample {
    public static void main(String[] args) {
        String filePath = "users.csv";

        try (Reader reader = new FileReader(filePath)) {
            CSVFormat format = CSVFormat.DEFAULT
                    .builder()
                    .setHeader()
                    .setSkipHeaderRecord(true)
                    .get();

            CSVParser csvParser = CSVParser.parse(reader, format);

            for (CSVRecord data : csvParser) {
                String id = data.get("ID");
                String name = data.get("Name");
                String email = data.get("Email");

                System.out.printf("ID: %s, Name: %s, Email: %s%n", id, name, email);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Breakdown

  • setSkipHeaderRecord(): Tells the parser to use the first row as column headers.
  • data.get("ColumnName"): Fetches the value under a specific column for each row.

You’ll see output like:

ID: 1, Name: Alice Johnson, Email: alice@example.com
ID: 2, Name: Bob Smith, Email: bob@example.com
ID: 3, Name: Carol White, Email: carol@example.com

Example Reading CSV by column position

Remove the header from users.csv.

1,Alice Johnson,alice@example.com
2,Bob Smith,bob@example.com
3,Carol White,carol@example.com
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class CSVReadByPosition {
    public static void main(String[] args) {
        String filePath = "user.csv";

        try (Reader reader = new FileReader(filePath)) {
            CSVFormat format = CSVFormat.DEFAULT.builder()
                    .setSkipHeaderRecord(false) // important: no header in the file
                    .get();

            CSVParser csvParser = CSVParser.parse(reader, format);

            for (CSVRecord data : csvParser) {
                String id = data.get(0);      // First column
                String name = data.get(1);    // Second column
                String email = data.get(2);   // Third column

                System.out.printf("ID: %s | Name: %s | Email: %s%n", id, name, email);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Expected Output

ID: 1 | Name: Alice Johnson | Email: alice@example.com
ID: 2 | Name: Bob Smith | Email: bob@example.com
ID: 3 | Name: Carol White | Email: carol@example.com

4. Handling Edge Cases

Fields with Commas or Quotes

Apache Commons CSV automatically handles tricky fields like:

csvPrinter.printRecord("4", "Tom, Jr.", "tom@example.com");

It will enclose the field in quotes:

"4","Tom, Jr.","tom@example.com"

Custom Delimiters

To use a semicolon instead of a comma:

CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';');

5. Tips for Working with CSV Files in Java

  • Always close resources: Use try-with-resources to ensure proper cleanup.
  • Validate headers: When reading, confirm that the expected headers are present.
  • Escape values carefully: Apache Commons CSV handles escaping for you — trust it.

6. Real-World Use Cases

Data Migration

You can use CSV writing to export data from a legacy system and then import it into a modern application.

Report Generation

Build scripts that generate periodic reports in CSV format for analytics or audit logs.

User Management

Bulk import/export user data via CSV, such as onboarding employees or syncing records with third-party systems.

Conclusion

Apache Commons CSV is a powerful and user-friendly library that streamlines reading and writing CSV files in Java. Whether working on a small project or an extensive enterprise application, this library allows you to manipulate CSV data with clarity and control.

Leave a Comment

Your email address will not be published. Required fields are marked *