Signup/Sign In
PUBLISHED ON: JANUARY 19, 2021

How to read a CSV file in Java

In this post, we are going to read a CSV file using the Java code. The CSV is a comma-separated file that is used to store data.

There are several ways by which we can read the CSV file such as using the Scanner class or OpenCSV library provided by the third party. You can download JAR files for opencsv here.

Here, we have two examples to understand the reading process of CSV file in Java.

We have a sample CSV file students.csv that is used for reading the data from Java.

// students.csv

101,'Rohan','India'
102,'Kumar','SriLanka'
103,'David','USA'

Time for an Example:

Let's create an example to read a CSV file. Here, we are using OpenCSV library and CSVReader class to read the file. The library is useful and built for CSV file handling.

import com.opencsv.*;
import java.io.FileReader;
import java.io.IOException;
public class Main {
	public static void main(String[] args){  
		String csvFile = "students.csv";
        CSVReader csvReader = null;
        try {
        	csvReader = new CSVReader(new FileReader(csvFile));
            String[] value;
            while ((value = csvReader.readNext()) != null) {
                System.out.println(value[0] + " " + value[1] + " " + value[2]);
            }
        } catch (IOException e) {
            System.out.println(e);
        }
	}
}


101 'Rohan' 'India'
102 'Kumar' 'SriLanka'
103 'David' 'USA'

Time for another Example:

However, there is another way to read the CSV file, using the Scanner class that is used to read the input from file or input resources. Here, we used Scanner class and useDelimeter() method to specify the value separator.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws FileNotFoundException{  
		//Reading file using scanner
        Scanner scanner = new Scanner(new File("students.csv"));
         
        //Comma as a delimiter
        scanner.useDelimiter(",");
       
        while (scanner.hasNext()) 
        {
            System.out.print(scanner.next() + " ");
        }
         
        // Closing the scanner  
        scanner.close();
	}
}


101 'Rohan' 'India'
102 'Kumar' 'SriLanka'
103 'David' 'USA'



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.