In this post, we will learn several approaches to read CSV file in Java programming language.

File reading is a fantastic capability that many programming languages offer, among the many features that modern programming languages offer.

But let us first see what CSV File is, how to create it, and its structure to store data.

What is CSV File?

CSV stands for Comma-Separated Values. It is just like another file, Which stores tabular data in it. The CSV File has a .csv extension.

How to Read CSV File in Java | Top 3 Methods | 2022 1
CSV File Format

A comma separates the values inside the file (,). A comma is a default separate among the values present in the CSV file.

This type of file can be easily imported and exported from applications, Which store the data in tabular formats such as Microsoft Office and Excel.

How to create a CSV File?

Now we will see how to create a CSV File. There are two methods by which we can create a CSV File. The two methods are listed below:

  • By Notepad
  • By Microsoft Excel

We will see both of the methods for creating CSV file one by one. Let us see first the method to create CSV File.

How to create a CSV File using MS Excel

1. First of all create a new sheet and create a database formally tabular data. An example of tabular data is below as an image.

How to Read CSV File in Java | Top 3 Methods | 2022 2
An Example of tabular Data

2. Save the file in CSV Format by giving it an appropriate name of your choice. In the picture below we are saving tabular data in CSV Format.

How to Read CSV File in Java | Top 3 Methods | 2022 3
Saving MS Excel sheet data as a CSV File

How to create a CSV File using Notepad:

CSV files can also be created using Notepad, Let us try to make some tabular data in Notepad, Which we can open in an Excel sheet.

The values in Notepad should be separated by a delimiter, Formally a comma(,). We insert the tabular data below in the image in Notepad File and then save it as a file in .csv format.

How to Read CSV File in Java | Top 3 Methods | 2022 4
Tabular Data in Notepad

After saving it as a file in .csv format. The file can be opened via Microsoft Excel. In the image below our file created in notepad having .csv format has opened in Microsoft Excel.

How to Read CSV File in Java | Top 3 Methods | 2022 5
.csv file opened in Microsoft, Which was created in Notepad

So far till now, We have seen What is CSV file, How it stores that data, and how to create it.

Now it’s time to discuss some methods by which we can read CSV Files in Java. So basically we will discuss three methods, Which are listed below.

  1. By Using Scanner

2. By String class

3. By OpenCSV library of Java

Let us discuss all three methods one by one.

1. Scanner Class to Read CSV File In Java

The scanner class contains a lot of in-built methods by which we can read a CSV File. First, We have to create an object of the Scanner class by putting a File type object containing the file’s location inside the Scanner constructor.

Then it breaks the data into the form of tokens and uses a delimiter as a separator between values. Then next() method provides the values of tabular Data.

Below the code is provided as a demonstration to read CSV Files using the Scanner class.

package newPackage;
import java.io.*;  
import java.util.Scanner;  
public class BeeTechnical 
{  
public static void main(String[] args) throws Exception  
{  
	
	//Creating a File type object containing Location of CSV File 
	File file = new  File("D:\\CSV_File.csv");
	
	//Scanner object containing file object in its Constructor
    Scanner sc = new Scanner(file);
    
    //Comma is assigned as a delimeter 
    sc.useDelimiter(",");   
    
    //sc.hasNext() returns boolean value true/false
    //Until there are some unread values in the CSV File,  
    while (sc.hasNext())  
    {   
    	//find and returns the complete token as values 	
       System.out.print(sc.next());   
    }
    
      //closing the scanner object
      sc.close();    
}  
}  

Output:

Read CSV File in Java,The output of the CSV File using the Scanner class
The output of the CSV File using the Scanner class
  • In the code above, First, we are making a File type object “file” by giving the location of the CSV File in the File’s Constructor.
  • Then we are putting this “file” object inside the Scanner class’s Constructor.
  • After that, we are running a While loop until there are some unread values present in the File. sc.hasNext() method will return false when there are no values left to read, this will terminate the condition of the while loop.

2. Read CSV File using String Class

We can use the .split() function of the string class, This function identifies the delimiters in File and then splits the rows into tokens.

This String.split() method returns an array of a string of present values inside the file. In this method, we use BufferedReader class until the EOF(End of File) character is reached.

package newPackage;
import java.io.BufferedReader;  
import java.io.FileReader;  
import java.io.IOException;  
public class BeeTechnical
{  
                 public static void main(String[] args)    
                 {  
	
                   //String "line" is initialized, Which will print a row of file 	
                    String line = "";

                   //String "splitBy" is initialized with Comma  
                    String splitBy = ",";  
                    
                    //Try Block
                    try   
                    {
                    	
                     //parsing a CSV file's location into BufferedReader class constructor  
                      BufferedReader br = new BufferedReader(new FileReader("D:\\CSV_File.csv"));  
                      
                      //br.readLine() returns boolean value true/false until there are
                      //no lines left to read
                      while ((line = br.readLine()) != null)  
                      {  
                    	  
                    	  // use comma as separator	  
                          String[] person = line.split(splitBy); 
                          
                          //Printing Line of CSV File
                          System.out.println("Person [First Name = " + person[0] + ", Last Name = " + person[1] + ", Age = " + person[2] + ", Salary = " + person[3]  +"]");  
                      }  
                     }   
                    
                    //Catch Block
                      catch (IOException e)   
                     {  
                       e.printStackTrace();  
                     }   
                     }  
                     } 

Output:

How to Read CSV File in Java | Top 3 Methods | 2022 6
The output of the CSV File using the Strint.split() function
  • In the code above, First, we are making an object “br” of BufferedReader class and putting a FileReader type object containing CSV File’s location, inside BufferedReader class’s Constructor.
  • Then, run a while loop till there are lines left to read inside CSV File.
  • Loop will terminate when there will no line to read further.

3. Read CSV File using OpenCSV API

It is a Third party API, Which contains numerous methods to read CSV Files. This library has some best methods to handle CSV Files as well.

package newPackage;
import java.io.FileReader;  
import com.opencsv.CSVReader;  
public class BeeTechnical 
{    
public static void main(String[] args)  
{  
	
	//Creating object of CSVReader Type 
    CSVReader reader = null;  
    
    //Try Block
    try  
    {  
    	
     //parsing CSV file's location into CSVReader class constructor  
     reader = new CSVReader(new FileReader("D:\\CSV_File.csv"));
     
     //String array nextLine is declared  
     String [] nextLine;
     
     
      //reads one line at a time, read.hasNext() will not return null 
      //until there are no lines left to read  
      while ((nextLine = reader.readNext()) != null)  
      {  
          
    	  for(String token : nextLine)  
          {  
           System.out.print(token);  
          }  
          System.out.print("\n");  
      }  
   }
    
    //Catch Block
    catch (Exception e)   
    {  
      e.printStackTrace();  
    }  
  }   
} 

Output:

How to Read CSV File in Java | Top 3 Methods | 2022 7
The output of CSV File using OpenCSV API

The output is the same as reading CSV Files using the Scanner class.

Conclusion:

In this article, We come to know what is a CSV File, Its structure for storing values, How to create it, and methods in Java to read CSV Files.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments