How to Parse a CSV file in Java

A CSV file is a simple text file used to store tabular data. Each line is a record of data and consists of fields separated by commas. The main advantage of CSV file format is that it is portable and human readable. Files using proprietary formats such as Microsoft excel files can be exported to CSV files for portability. The following Java program parses simple CSV files,

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;

// Sample Java program to read simple CSV files
public class SimpleCSVReader {

    public static void main(String[] args) throws Exception {
        // Replace FileReader parameter with the actual path
        BufferedReader reader = new BufferedReader(new FileReader("input.csv"));
        String line;
        while ((line=reader.readLine()) != null) {
            String[] fields = line.split(",");
            // Print the columns in array form
            System.out.println(Arrays.toString(fields));
        }
        reader.close();
    }

}

Sometimes the fields in the CSV file may contain commas. In order to distinguish commas in data fields from field separators, the fields are usually surrounded by quotes. The above program won’t work with such complex CSV files. The following Java program shows how the Apache Commons CSV library can be used to parse such complex CSV files.

You can download Apache Commons CSV library from here. Extract the zip file and then ensure that the jar file commons-csv-1.4.jar is in the classpath. For example, you can use the following commands to compile and run the program if the jar file is present in the same folder containing the Java file ApacheCSVReader.java. Note that the commands are slightly different depending on your operating system.

To compile in linux/mac,

javac -cp "commons-csv-1.4.jar:." ApacheCSVReader.java

To compile in Windows,

javac -cp "commons-csv-1.4.jar;." ApacheCSVReader.java

To run in linux/mac,

java -cp "commons-csv-1.4.jar:." ApacheCSVReader

To run in Windows,

java -cp "commons-csv-1.4.jar;." ApacheCSVReader
import java.io.FileReader;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

// Java program to parse CSV files using Apache CSV Reader
// Can read CSV files with commas in quoted fields
public class ApacheCSVReader {

    public static void main(String[] args) throws Exception {
        FileReader in = new FileReader("input.csv");
        Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
        for (CSVRecord record : records) {
            for (String s : record) {
                System.out.print(s + "|");
            }
            System.out.println();
        }
    }
}

To test the above program, you can use the following sample CSV file (input.csv). Ensure that it is saved in the same folder where Java class files are stored.

India,Sri Lanka, Nepal
"Hi, There","Another message","Greeting"
200, 400,600

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply