How to Read CSV file in Java

In past articles, we studied how to read an excel file in Java. In this article, we will discuss how to read a CSV file in Java using different methods. The data is multiplying with time; all such data is kept in these CSV files.

There is a need to understand the techniques to read these files using Java. We will learn all such methods in this article. So, let’s start discussing this topic.

What is CSV file?

The CSV file stands for the Comma-Separated Values file. It is a simple plain-text file format that stores tabular data in columns in simple text forms, such as a spreadsheet or database, and splits it by a separator. The separator used to split the data usually is commas (,).

We can import files in the CSV format and export them using programs like Microsoft Office and Excel, which store data in tables. The CSV file uses a delimiter to identify and separate different data tokens in a file.

The use of the CSV file format is when we move tabular data between programs that natively operate on incompatible formats.

Creating CSV File

We can create a CSV file in the following two ways:

  • Using Microsoft Excel
  • Using Notepad editor

Follow TechVidvan on Google & Stay updated with latest technology trends

1. Using Microsoft Excel

1: Open Microsoft Excel.

2: Write the data into the excel file:

create csv file in java

3: Save the excel file with .csv extension as shown below:

save csv file in java

2. Using Notepad

We can also create a CSV file using Notepad with the following steps:

Step 1: Open Notepad editor.

Step 2: Write some data into file separated by comma (,).

For example:
Rajat, Jain, 26, 999967439, Delhi

Step 3: Save the file with .csv extension.
We have created the following file.

CSV file in java

Ways to read CSV file in Java

There are the following four ways to read a CSV file in Java:

read CSV file in Java

1. Java Scanner class

The Scanner class of Java provides various methods by which we can read a CSV file. It provides a constructor that produces values scanned from the specified CSV file. This class also breaks the data in the form of tokens.

There is a delimiter pattern, which, by default, matches white space. Then, using different types of next() methods, we can convert the resulting tokens.

Code to read a CSV file using a Scanner class:

import java.io. * ;
import java.util.Scanner;
public class CSVReaderDemo {
  public static void main(String[] args) throws Exception {
    Scanner sc = new Scanner(new File("C:\\Users\\Dell\\Desktop\\csvDemo.csv"));
    //parsing a CSV file into the constructor of Scanner class 
    sc.useDelimiter(",");
    //setting comma as delimiter pattern
    while (sc.hasNext()) {
      System.out.print(sc.next());
    }
    sc.close();
    //closes the scanner  
  }
}

Output:

Mr., Raju, Dixit, 3603286012, Burdwan
Mr., Joseph, Patil, 4645968519, Hoogly
Mr., Andrew, Mukherjee, 9067215139, Burmingham
Mr., Varun, Patel, 2503595381, Sindh
Mr., Michael, Baldwin, 7631068844, Kentucky
Mr., Emmanuel, Agarwal, 3538037535, Nice
Mr., Sumeet, Patil, 6871075256, Aukland
Mr., Pranab, Kulkarni, 7982264359, Hubli
Mr., Rajeev, Singh, 3258837884, Patiala
Mr., Sujay, Kapoor, 5127263160, Mumbai

2. Java String.split() method

The String.split() of Java identifies the delimiter and split the rows into tokens.

The Syntax of this method is:

public String[] split(String regex)

Code to read a CSV file using String.split() method:

import java.io. * ;
public class CSVReader {
  public static final String delimiter = ",";
  public static void read(String csvFile) {
    try {
      File file = new File(csvFile);
      FileReader fr = new FileReader(file);
      BufferedReader br = new BufferedReader(fr);
      String line = " ";
      String[] tempArr;
      while ((line = br.readLine()) != null) {
        tempArr = line.split(delimiter);
        for (String tempStr: tempArr) {
          System.out.print(tempStr + " ");
        }
        System.out.println();
      }
      br.close();
    }
    catch(IOException ioe) {
      ioe.printStackTrace();
    }
  }
  public static void main(String[] args) {
    //csv file to read
    String csvFile = "C:\\Users\\Dell\\Desktop\\csvDemo.csv";
    CSVReader.read(csvFile);
  }
}

Output:

Mr., Raju, Dixit, 3603286012, Burdwan
Mr., Joseph, Patil, 4645968519, Hoogly
Mr., Andrew, Mukherjee, 9067215139, Burmingham
Mr., Varun, Patel, 2503595381, Sindh
Mr., Michael, Baldwin, 7631068844, Kentucky
Mr., Emmanuel, Agarwal, 3538037535, Nice
Mr., Sumeet, Patil, 6871075256, Aukland
Mr., Pranab, Kulkarni, 7982264359, Hubli
Mr., Rajeev, Singh, 3258837884, Patiala
Mr., Sujay, Kapoor, 5127263160, Mumbai

3. Using BufferedReader class in Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CSV {
  public static void main(String[] args) {
    String line = "";
    String splitBy = ",";
    try {
      //parsing a CSV file into BufferedReader class constructor  
      BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Dell\\Desktop\\csvDemo.csv"));
      while ((line = br.readLine()) != null)
      //returns a Boolean value  
      {
        String[] employee = line.split(splitBy);
        //use comma as separator  
        System.out.println("Emp[First Name=" + employee[1] + ", Last Name=" + employee[2] + ", Contact=" + employee[3] + ", City= " + employee[4] + "]");
      }
    }
    catch(IOException e) {
      e.printStackTrace();
    }
  }
}

Output:

Emp[First Name= Raju, Last Name= Dixit, Contact= 3603286012, City= Burdwan]
Emp[First Name=Joseph, Last Name=Patil, Contact= 4645968519, City= Hoogly]
Emp[First Name=Andrew, Last Name=Mukherjee, Contact= 9067215139, City= Burmingham]
Emp[First Name=Varun, Last Name=Patel, Contact= 2503595381, City= Sindh]
Emp[First Name=Michael, Last Name=Baldwin, Contact= 7631068844, City= Kentucky]
Emp[First Name=Emmanuel, Last Name=Agarwal, Contact= 3538037535, City= Nice]
Emp[First Name=Sumeet, Last Name=Patil, Contact= 6871075256, City= Aukland]
Emp[First Name=Pranab, Last Name=Kulkarni, Contact= 7982264359, City= Hubli]
Emp[First Name=Rajeev, Last Name=Singh, Contact= 3258837884, City= Patiala]
Emp[First Name=Sujay, Last Name=Kapoor, Contact= 5127263160, City= Mumbai]

4. Using OpenCSV API in Java

OpenCSV API is a third party API. This API provides standard libraries to read various versions of the CSV file. The OpenCSV API also offers better control to handle the CSV files. This library can also read Tab-Delimited File or TDF file format.

Features of Java OpenCSV API

  • Can read Any number of values per line.
  • Avoids commas in quoted elements.
  • Can handle entries that span multiple lines.

We use the CSVReader class to read a CSV file. The class CSVReader provides a constructor to parse a CSV file.

Steps to read Java CSV file in eclipse:

1: Create a class file with the name CSVReaderDemo and write the following code.
2: Create a lib folder in the project.
3: Download opencsv-3.8.jar
4: Copy the opencsv-3.8.jar and paste into the lib folder.
5: Run the program.

Code to read a CSV file using OpenCSV API:

import java.io.FileReader;
import com.opencsv.CSVReader;
public class CSVReaderDemo {
  public static void main(String[] args) {
    CSVReader reader = null;
    try {
      //parsing a CSV file into CSVReader class constructor  
      reader = new CSVReader(new FileReader("C:\\Users\Dell\Desktop\csvDemo.csv"));
      String[] nextLine;
      //reads one line at a time  
      while ((nextLine = reader.readNext()) != null) {
        for (String token: nextLine) {
          System.out.print(token);
        }
        System.out.print("\n");
      }
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
}

Output:

Mr. Raju Dixit 3603286012 Burdwan
Mr. Joseph Patil 4645968519 Hoogly
Mr. Andrew Mukherjee 9067215139 Burmingham
Mr. Varun Patel 2503595381 Sindh
Mr. Michael Baldwin 7631068844 Kentucky
Mr. Emmanuel Agarwal 3538037535 Nice
Mr. Sumeet Patil 6871075256 Aukland
Mr. Pranab Kulkarni 7982264359 Hubli
Mr. Rajeev Singh 3258837884 Patiala
Mr. Sujay Kapoor 5127263160 Mumbai

Reading Java CSV file with a different separator

We can also read a file using a different delimiter. In the following CSV file, we have created a CSV file using a semicolon (;) to separate tokens.

reading csv in java

Code to read a CSV file with different delimiters:

import java.io.FileReader;
import java.io.IOException;
import com.opencsv.CSVReader;
public class CSV {
  public static void main(String[] args) {
    CSVReader reader = null;
    try {
      reader = new CSVReader(new FileReader("C:\\Users\\Dell\\Desktop\\csvDemo.csv"));
      String[] nextLine;
      //read one line at a time  
      while ((nextLine = reader.readNext()) != null) {
        for (String token: nextLine) {
          System.out.println(token);
        }
        System.out.print("\n");
      }
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
}

Output:

Mr.; Raju; Dixit; 3603286012; Burdwan
Mr.; Joseph; Patil; 4645968519; Hoogly
Mr.; Andrew; Mukherjee; 9067215139; Burmingham
Mr.; Varun; Patel; 2503595381; Sindh
Mr.; Michael; Baldwin; 7631068844; Kentucky
Mr.; Emmanuel; Agarwal; 3538037535; Nice
Mr.; Sumeet; Patil; 6871075256; Aukland
Mr.; Pranab; Kulkarni; 7982264359; Hubli
Mr.; Rajeev; Singh; 3258837884; Patiala
Mr.; Sujay; Kapoor; 5127263160; Mumbai

Conclusion

In this Java tutorial, we have learned different ways to read CSV file in Java. We can use any one of the three methods to read Java CSV file. Java OpenCSV API is an in-built API in eclipse that we can use to read CSV files. These all ways to read and write CSV files in Java are the simplest Core Java components.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *