Thursday, June 13, 2013

Read CSV file and parse

 
 
package com;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.apache.commons.csv.CSVParser;

import au.com.bytecode.opencsv.CSVReader;

public class ReadCSVFileAndSplit {

 /**
  * @param args
  */
 public static void main(String[] args) {
  BufferedReader br = null;
   
  try {
 
   String sCurrentLine;
   String[] values = null;
   br = new BufferedReader(new FileReader("C:\\testing.csv"));
 
   while ((sCurrentLine = br.readLine()) != null) {
    values = sCurrentLine.split(",");
   }
   for (String str  : values){
    System.out.println(str);
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (br != null)br.close();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }
  
  System.out.println("************Using CSVReader from opencsv API************");
  CSVReader reader;
  try {
   reader = new CSVReader(new FileReader("C:\\testing.csv"));
   String[] myEntries = reader.readNext();
  
   for (String str  :  myEntries){
    System.out.println(str);
   }
   
  } catch (IOException e) {
   e.printStackTrace();
  }
  System.out.println("************Using CSVParser from apache common csv API************");
   try {
   CSVParser csvParser = new CSVParser(new FileReader("C:\\testing.csv"));
   String[] myEntries = csvParser.getLine();
   
   for (String str  :  myEntries){
    System.out.println(str);
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
     
 }

} 
pom.xml
 
<project>
............
 <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
   
  </build>
  <dependencies>
  <dependency>
 <groupId>org.apache.solr</groupId>
 <artifactId>solr-commons-csv</artifactId>
 <version>3.5.0</version>
</dependency>
<dependency>
 <groupId>net.sf.opencsv</groupId>
 <artifactId>opencsv</artifactId>
 <version>2.3</version>
</dependency>
  </dependencies>
</project> 


output:

test
me
for
free
************Using CSVReader from opencsv API************
test
me
for
free
************Using CSVParser from apache common csv API************
test
me
for
free 
 
 
 
Note : 
 
I have used both : solr-commons-csv-3.5.0.jar & opencsv-2.3.jar

 

No comments: