Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Reading a CSV File in Java

CSV stands for Comma Separated Values and is a very popular file type. CSV files are used to store information delimited by commas. Each row of the file is used to represent a data record. In this tutorial, we will learn how to read a CSV file and copy its content into an array or list. For this tutorial, we will use a simple CSV file that contains just three records. The contents of the file are shown below.

Justin, 101, 9.1
Jessica, 102, 8.7
Clark, 103, 7.1

Reading CSV Files by Using BufferedReader

The BufferedReader class of the java.io package can be used to read a basic CSV file. We will simply read each line of the file by using the readLine() method. Then we can split the line using the split() method and passing the comma as a delimiter.

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class ReadingCSV
{
	public static void main(String[] args)
	{
		try
		{
			List< List<String> > data = new ArrayList<>();//list of lists to store data
			String file = "C:\\Users\\Lenovo\\Desktop\\demo.csv";//file path
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			
			//Reading until we run out of lines
			String line = br.readLine();
			while(line != null)
			{
				List<String> lineData = Arrays.asList(line.split(","));//splitting lines
				data.add(lineData);
				line = br.readLine();
			}
			
			//printing the fetched data
			for(List<String> list : data)
			{
				for(String str : list)
					System.out.print(str + " ");
				System.out.println();
			}
			br.close();
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


Justin 101 9.1
Jessica 102 8.7
Clark 103 7.1

Note that we cannot use this approach to read more complex CSV files or files in which the comma itself is a value. For example, consider a CSV file in which the second column is used to store punctuation marks.

Full Stop,"."
Comma,","
Exclamation,"!"

If we try to read this file, then the following data is stored in the lists. We can see that no value is stored for the second row of the file(the comma has been omitted). We also don't require the quotation marks.


Full Stop "."
Comma " "
Exclamation "!"

Reading CSV Files by Using the Scanner Class

We can also use the Scanner class of java.util package to read a CSV file. This approach is quite similar to that of BufferedReader. We will simply read each line of the file and then split it by using the comma as a delimiter. Then we can store individual records in a list of lists.

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Arrays;
public class ReadingCSV
{
	public static void main(String[] args)
	{
		try
		{
			List< List<String> > data = new ArrayList<>();//list of lists to store data
			String filePath = "C:\\Users\\Lenovo\\Desktop\\demo.csv";//file path
			File file = new File(filePath);
			Scanner s = new Scanner(file);			
			//Reading until we run out of lines
			while(s.hasNextLine())
			{
				List<String> lineData = Arrays.asList(s.nextLine().split(","));//splitting lines
				data.add(lineData);
			}			
			//printing the fetched data
			for(List<String> list : data)
			{
				for(String str : list)
					System.out.print(str + " ");
				System.out.println();
			}
			s.close();
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


Justin 101 9.1
Jessica 102 8.7
Clark 103 7.1

Just like the BufferedReader, the Scanner class approach cannot be used for complex CSV files.

Reading CSV Files by Using the OpenCSV Library

OpenCSV is a CSV file parsing library that can make reading from CSV files a lot easier. The CSVReader is used as a wrapper around a FileReader. We will use the readNext() method of CSVReader to read the file line by line. It returns an array of strings and we don't need to worry about splitting the line.

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.opencsv.CSVReader;
import java.util.Arrays;
public class ReadingCSV
{
	public static void main(String[] args)
	{
		try
		{
			List< List<String> > data = new ArrayList<>();//list of lists to store data
			String filePath = "C:\\Users\\Lenovo\\Desktop\\demo.csv";//file path
			FileReader fr = new FileReader(filePath);
			CSVReader reader = new CSVReader(fr);
			
			String[] lineData = reader.readNext();
			//Reading until we run out of lines
			while(lineData != null)
			{
				data.add(Arrays.asList(lineData));
				lineData = reader.readNext();
			}
			
			//printing the fetched data
			for(List<String> list : data)
			{
				for(String str : list)
					System.out.print(str + " ");
				System.out.println();
			}
			reader.close();
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


Justin 101 9.1
Jessica 102 8.7
Clark 103 7.1

Let's use the above code for the CSV file in which we had a cell whose value was a comma. As we can see, the comma is considered as a value and not a delimiter by the CSVReader. Even the quotations are removed and the data is presented in a better format.


Full Stop .
Comma ,
Exclamation !

Summary

A CSV file is used to store data delimited by a comma(or a semicolon in some cases). Each line of a CSV file represents a record. We can easily read data from basic CSV files by using BufferedReader or Scanner. But we may not get the expected results when reading a more complicated CSV file. The easiest way to read a CSV file is to use an external library like OpenCSV.