Working with csv files in Java


OpenCSV has to be installed first, which is a parser library for Java. The dependency has to be mentioned in the pom.xml file in the maven project. After that, the below code can be utilized.

Example

import java.io.FileReader;
import java.io.*;
public class Demo{
   public static void readDataLineByLine(String file){
      try{
         FileReader my_filereader = new FileReader(file);
         CSVReader csvReader = new CSVReader(my_filereader);
         String[] nextRecord;
         while ((nextRecord = csvReader.readNext()) != null){
            for (String cell : nextRecord){
               System.out.print(Output + "\t");
            }
            System.out.println();
         }
      }
      catch (Exception e){
         e.printStackTrace();
      }
   }
}

Output

Prints data in a csv file line by line

A class named Demo contains a function named ‘readDataLineByLine’ that takes a file as parameter. A FileReader instance is created, and a CSVReader instance is created, that reads the elements in the CSV file. Every line is read one by one and displayed on the screen. This is written in the try block, and exceptions (if any) are caught in the ‘catch’ block.

Updated on: 17-Aug-2020

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements