Reading CSV file using Java Code

CSV:CSV is a comma separated values file, which allows data to be saved in a table structured format. CSVs look like a garden-variety spreadsheet but with a .csv extension (Traditionally they take the form of a text file containing information separated by commas, hence the name).(Source Wiki)

If someone opens CSV with notepad or textpad or some other editor it may look clumsy and difficult to read,Its always a good idea to open it using MS Excel for easy formatting and readability.


Below is the Java code to read from CSV file, herein we are trying to read each line from csv file, splitting it by delimiter comma and saving each item in a String array.

CSVFile.csv
This,is,code,for,reading,csv,file
this,is,first,line
this,is,second,line
this,is,third,line



****************************************************************************************

package test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;


public class ReadCSV {
  public static void main(String args[])
   {
   
  ReadCSV test = new ReadCSV();
  test.readCSV();

    }
  public void readCSV()
  {
  String filename = "C:\\CSVFile.csv";
    BufferedReader csvFileReader = null;
    String line = "";
    String[] readLine;
  try {

  csvFileReader = new BufferedReader(new FileReader(filename));
  int k=0;
  while ((line = csvFileReader.readLine()) != null) {
  
  System.out.println("Line" + "  "+ k + "  " + "Starts from here" + "*******************");  
      
         readLine = line.split(",");
         for(int i=0; i< readLine.length;i++)
         {
                     
          System.out.println("readLine"+ "[" + i + "]" + "  "+ readLine[i]);
          
         }
         System.out.println("*********************************************");
         k++;
  }

}
  
  catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
} finally {
  if (csvFileReader != null) {
         try {
          csvFileReader.close();
         } catch (IOException e) {
               e.printStackTrace();
         }
  }
}
  }
}


==============================================


Output:
Line  0  Starts from here*******************
readLine[0]  This
readLine[1]  is
readLine[2]  code
readLine[3]  for
readLine[4]  reading
readLine[5]  csv
readLine[6]  file
*********************************************
Line  1  Starts from here*******************
readLine[0]  this
readLine[1]  is
readLine[2]  first
readLine[3]  line
*********************************************
Line  2  Starts from here*******************
readLine[0]  this
readLine[1]  is
readLine[2]  second
readLine[3]  line
*********************************************
Line  3  Starts from here*******************
readLine[0]  this
readLine[1]  is
readLine[2]  third
readLine[3]  line
*********************************************




Comments

Popular Posts