How to Read CSV File in Java

The CSV stands for Comma-Separated Values. It is a simple file format which is used to store tabular data in simple text form, such as a spreadsheet or database.

The files in the CSV format can be imported to and exported from programs (Microsoft Office and Excel) which store data in tables. The CSV file used a delimiter to identify and separate different data token in a file.

The CSV file format is used when we move tabular data between programs that natively operate on incompatible formats. There are following ways to read CSV file in Java. The default separator of a CSV file is a comma (,).

Read CSV file using Apache Commons CSV

Here in this example we will read csv file in java by using the Apache Commons CSV library.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.techblogstation</groupId>
  <artifactId>ReadCSVFiles</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
  <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-csv -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.7</version>
</dependency>
  </dependencies>
</project>

Reading a CSV file records by column index:

Sample CSV File

Name,Phone,Country
Rahul,986525689,India
Sam,852647182,Germany

We have created a BufferedReader for the file and passed it to CSVParser with the default CSV format. And once we get the CSVParser then we can iterate over records one by one using a for loop.

Program for this is:

package com.techblogstation.csv;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ReadCSVFile 
{

	private static final String FILE_PATH = "E:\\Files\\Employees.csv";
	public static void main(String[] args) throws IOException
	{
		// using try with resources
		try (
	            Reader reader = Files.newBufferedReader(Paths.get(FILE_PATH));
	            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
	        ) {
	            for (CSVRecord csvRecord : csvParser) {
	                // Getting values by Column Index
	                String name = csvRecord.get(0);
	                String phone = csvRecord.get(1);
	                String country = csvRecord.get(2);
	               

	                System.out.println("Record Number - " + csvRecord.getRecordNumber());
	                
	                System.out.println("Name : " + name);
	                System.out.println("Phone : " + phone);
	                
	                System.out.println("Country : " + country);
	                System.out.println("\n");
	            }
		
	}

}
}
##Output##
Record Number - 1
Name : Rahul
Phone : 986525689
Country : India

Record Number - 2
Name : Sam
Phone : 852647182
Country : Germany

Reading a CSV file records by column name:

The ignoreHeaderCase is used to not make the header names case-sensitive and the trim method is used to trim leading and trailing blank spaces from the values.

package com.techblogstation.csv;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ReadCSVFile 
{

	private static final String FILE_PATH = "E:\\Files\\Employees.csv";
	public static void main(String[] args) throws IOException
	{
		// using try with resources
		try (
	            Reader reader = Files.newBufferedReader(Paths.get(FILE_PATH));
				CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT
	                    .withHeader("Name","Phone","Country")
	                    .withIgnoreHeaderCase()
	                    .withTrim().withSkipHeaderRecord());
	        ) {
	            for (CSVRecord csvRecord : csvParser) {
	                // Getting values by Name of each column
	                String name = csvRecord.get("Name");
	                String phone = csvRecord.get("Phone");
	                String country = csvRecord.get("Country");
	               

	                System.out.println("Record Number - " + csvRecord.getRecordNumber());
	                
	                System.out.println("Name : " + name);
	                System.out.println("Phone : " + phone);
	                
	                System.out.println("Country : " + country);
	                System.out.println("\n");
	            }
		
	}

}
}
 ##Output##
Record Number - 1
Name : Rahul
Phone : 986525689
Country : India

Record Number - 2
Name : Sam
Phone : 852647182
Country : Germany

Read CSV file using OpenCSV

Here in this example we will read csv file in java by using the OpenCSV library

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.techblogstation</groupId>
  <artifactId>ReadCSVFiles</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
 <!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.0</version>
</dependency>
 
 </dependencies>
</project>

Read Records one by one

package com.techblogstation.csv;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;

import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ReadCSVFile 
{

	private static final String FILE_PATH = "E:\\Ashish\\Files\\Employees.csv";
	public static void main(String[] args) throws IOException, CsvValidationException
	{
		// using try with resources
		try (
	            Reader reader = Files.newBufferedReader(Paths.get(FILE_PATH));
				CSVReader csvReader = new CSVReader(reader);
	        ) {
			// Fetching Records One by One in a String array
               String[] csvRecord;
               while ((csvRecord = csvReader.readNext()) != null) 
               {
                   System.out.println("Name : " + csvRecord[0]);
                   System.out.println("Phone : " + csvRecord[1]);
                   System.out.println("Country : " + csvRecord[2]);
                   
                  
               }
		
	}

}
}

Conclusion

Readers you have learned how to read a csv file in java using apache commons csv and open csv api.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply