Sunday, January 9, 2011

Read CSV using java API


In this post, we are going to read CSV file using Java API.

A comma-separated values or character-separated values (CSV) file is a simple text format for a database table. Each record in the table is one line of the text file.

I am going to use opencsv API for parsing CSV file.

opencsv is an lightweight csv parsing and writing library for Java under an Apache 2.0 license. 
Download API : Click Here
Features of opencsv
opencsv supports all the basic csv-type things you're likely to want to do:
  • Arbitrary numbers of values per line
  • Ignoring commas in quoted elements
  • Handling quoted entries with embedded carriage returns (ie entries that span multiple lines)
  • Configurable separator and quote characters (or use sensible defaults)
  • Read all the entries at once, or use an Iterator style model
  • Creating csv files from String[] (ie. automatic escaping of embedded quote chars)



This class is used to read the CSV file.


package com.sarf.business;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import au.com.bytecode.opencsv.CSVReader;

public class ReadCSVFileData
{    
      public void readCSVFile(String pstrFileName)
      {
            CSVReader reader;
            String  nextLine[]=new String[1000];
            FileReader fr =  null;
            try
            {
                fr = new FileReader(pstrFileName);
                reader = new CSVReader(fr);
             
                while ((nextLine = reader.readNext()) != null)
                {
                  for(int nIndex = 0; nIndex <nextLine.length;nIndex++)
                  {
                        System.out.print(nextLine[nIndex]+" ");
                  }
                  System.out.println();
                }
             }
            catch (Exception e)
            {
                  e.printStackTrace();
            }
      }
}



This is our main class which will call  ReadCSVFileData.java methods.

package com.sarf.business;
public class ReadCSVMain
{
      public static void main(String[] args)
      {
            String strFilePath = "K:/test.csv";
            ReadCSVFileData objRCFD = new ReadCSVFileData();
            objRCFD.readCSVFile(strFilePath);
      }
}