Site icon Narayana Tutorial

CSV File Read Line By Line

CSV File Writing By ResultSet

CSV File Writing By ResultSet

CSV File Read Line By Line

In the post I am going to explaining CSV file read line by line by using opencsv jar file. You can see what is CSV file?.

Before going to write java program we need to download opencsv jar file.

Find the below sample data and save it in the format of csv file extension.

How to create csv file

  1. Open note pad
  2. Paste the below data into note pad
  3. Save it as like “OpenCsvRead.csv” in the double quote as file name.
FIRSTNAME,LASTNAME,AGE
Narayana,Ragi,30
Kumar,Chitra,50
Swamy,Bathala,40

Find the below java program will read the above data line by line with splitting comma separated values by default means that no need to mention the comma in the program. It will read csv file line by line, in each line values will be splitted and putting into string array and the array will be iterated like one iteration for one line.

package com.narayanatutorial.opencsv;

import au.com.bytecode.opencsv.CSVReader;
import java.io.FileReader;

public class OpenCsvReadLineByLine {

    public static void main(String args[]) {
       String csvFilename = "D:/narayanatutorial/SampleFiles/OpenCSVRead.csv";
        try {
            CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
            String[] csvrow = null;
            while ((csvrow = csvReader.readNext()) != null) {
                System.out.println(csvrow[0]
                        + " # " + csvrow[1]
                        + " #  " + csvrow[2]);
            }
        } catch (Exception e) {
            System.out.println("exception :" + e.getMessage());
        }

    }
}

Copy the above java program into your IDE and execute then see the output as follows

Output

FIRSTNAME # LASTNAME #  AGE
Narayana # Ragi #  30
Kumar # Chitra #  50
Swamy # Bathala #  40

you can find the above sample program in the github. If you have git account you can download from github and other sample programs also available and find the below github link to download. We used Netbeans IDE to develop sample programs. So you can directly import into Netbeans if you are having Netbeans else create sample project in your IDE and replace src folder.

Git link

I hope you understand CSV File Read Line By Line by using opencsv jar file.