SoFunction
Updated on 2025-04-14

A detailed explanation of how Java uses commons-csv to handle CSV file operations

In Java development, processing CSV (comma-separated values) files is a common task. The Apache Commons CSV library is a very powerful and easy-to-use tool that allows us to read, write, and manipulate CSV files easily. Next, I will tell you in detail how to use the commons-csv library.

1. Introduce commons-csv library

First, you have to add the commons-csv library to your project. If you are using a Maven project, add the following dependencies to the file:

<dependency>
    <groupId></groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.9.0</version>
</dependency>

2. Read CSV file

Here is a sample code for reading CSV files using the commons-csv library:

import ;
import ;
import ;
 
import ;
import ;
import ;
 
public class ReadCSVExample {
    public static void main(String[] args) {
        try {
            // Create a Reader object to read CSV files            Reader in = new FileReader("");
 
            // Use to parse CSV files            CSVParser parser = new CSVParser(in, );
 
            // traverse every line of the record in the CSV file            for (CSVRecord record : parser) {
                // Iterate through every field of the current record                for (String field : record) {
                    (field + "\t");
                }
                ();
            }
 
            // Close the parser            ();
        } catch (IOException e) {
            ();
            ("CSV file reading failed:" + ());
        }
    }
}

Code explanation:

Reader in = new FileReader("");: Creates a FileReader object to read files.

CSVParser parser = new CSVParser(in, );: Use to parse CSV files and create a CSVParser object.

for (CSVRecord record : parser): Iterates through each row of records in the CSVParser. CSVRecord represents a row of data.

for (String field: record): Iterate through each field of the current record and print it out.

();: Close CSVParser and release resources.

3. Write to CSV file

Next is the sample code to write to a CSV file using the commons-csv library:

import ;
import ;
 
import ;
import ;
import ;
 
public class WriteCSVExample {
    public static void main(String[] args) {
        try {
            // Create a Writer object for writing to a CSV file            Writer out = new FileWriter("");
 
            // Use to create CSVPrinter object            CSVPrinter printer = new CSVPrinter(out, );
 
            // Write to the header            ("Name", "Age", "City");
 
            // Write data rows            ("John", "25", "New York");
            ("Jane", "30", "Los Angeles");
 
            // Refresh and close CSVPrinter            ();
            ();
 
            ("CSV file was written successfully!");
        } catch (IOException e) {
            ();
            ("CSV file writing failed:" + ());
        }
    }
}

Code explanation:

Writer out = new FileWriter("");: Creates a FileWriter object for writing to a file.

CSVPrinter printer = new CSVPrinter(out, );: Use to create a CSVPrinter object to write to a CSV file.

("Name", "Age", "City");: Write to the header of the CSV file.

("John", "25", "New York");: Write a line of data.

(); ();: Flush the buffer and close CSVPrinter to ensure that data is written to the file.

4. Customize CSV format

The commons-csv library also allows us to customize the format of CSV files, such as specifying delimiters, quote characters, etc. Here is an example:

import ;
import ;
 
import ;
import ;
import ;
 
public class CustomCSVFormatExample {
    public static void main(String[] args) {
        try {
            // Create a Writer object for writing to a CSV file            Writer out = new FileWriter("custom_output.csv");
 
            // Customize CSV format, use semicolons as delimiter            CSVFormat customFormat = (';');
 
            // Create CSVPrinter object using custom format            CSVPrinter printer = new CSVPrinter(out, customFormat);
 
            // Write to the header            ("Name", "Age", "City");
 
            // Write data rows            ("John", "25", "New York");
            ("Jane", "30", "Los Angeles");
 
            // Refresh and close CSVPrinter            ();
            ();
 
            ("Custom format CSV file was written successfully!");
        } catch (IOException e) {
            ();
            ("CSV file writing failed:" + ());
        }
    }
}

Code explanation:

CSVFormat customFormat = (';');: Customize CSV format, using a semicolon as a separator.

CSVPrinter printer = new CSVPrinter(out, customFormat);: Create CSVPrinter objects using a custom format.

The above is a detailed explanation of how Java uses commons-csv to handle CSV file operations. For more information about Java commons-csv operating CSV, please pay attention to my other related articles!