Monday, June 29, 2009

Reading CSV Files Using csvjava 2.0

Recently I have gone through a new CSV Reader called csvjava 2.0 It is a very simple tool which has only 2 classes CSVReader and CSVWritter but yet very powerful. Below I have wrote one sample program using CSVReader class of csvjava 2.0.

This CSV Reader supports all escapping that has been supported by CSV file format.

e.g.
Hi Vijayan This is a Test,"""Simple Test with , and """,A,B,CV
Will be treated as follows
Column 1: Hi Vijayan This is a Test
Column 2: "Simple Test with , and ""
Column 3: A
Column 4: B
Column 5: CV

import java.io.FileNotFoundException;
import java.io.IOException;

import com.csvreader.CsvReader;


public class CSVReaderSample {

public static void main(String[] args) {
try {
CsvReader reader=new CsvReader("Vijayan.csv");

while(reader.readRecord()){
System.out.print(reader.getCurrentRecord()+")");
System.out.print(reader.get(0));
System.out.print("\t");
System.out.print(reader.get(1));
System.out.print("\t");
System.out.print(reader.get(2));
System.out.print("\t");
System.out.print(reader.get(3));
System.out.print("\t");
System.out.println(reader.get(4));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

No comments: