How to read the data from a CSV file in Java?

JavaObject Oriented ProgrammingProgramming

A CSV stands for Comma Separated Values. In a CSV file, each line contains words that are separated with a comma(,) and it is stored with a .csv extension.

We can read a CSV file line by line using the readLine() method of BufferedReader class. Split each line on comma character to get the words of the line into an array. Now we can easily print the contents of the array by iterating over it or by using an appropriate index.

CSV File

Example

import java.io.*;
public class CSVReaderTest {
   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:/Temp/Technology.csv";
       CSVReaderTest.read(csvFile);
   }
}

Output

"JAVA" "PYTHON" "JAVASCRIPT" "SELENIUM" "SCALA"
raja
Published on 16-Aug-2019 18:12:38
Advertisements