Read CSV
Super CSV is a free library for reading and writing
CSV files in Java. We need to have SuperCSV-1.52.jar, spiffy-0.05.jar or
later versions in classpath.
The following example shows reading a CSV file line by line using Super CSV.
test1.csv
aaaa,bbbb,cccc,dddd
one,two,three,four
package com.bethecoder.tutorials.super_csv.tests;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import org.supercsv.io.CsvListReader;
import org.supercsv.prefs.CsvPreference;
public class ReadCSV {
/**
* @param args
* @throws IOException
*/
public static void main ( String [] args ) throws IOException {
/**
* Load CSV from classpath
*/
CsvListReader csvReader = new CsvListReader ( new InputStreamReader (
ReadCSV. class .getClassLoader () .getResourceAsStream ( "test1.csv" )) ,
CsvPreference.STANDARD_PREFERENCE ) ;
List<String> rowAsTokens;
while (( rowAsTokens = csvReader.read ()) != null ) {
System.out.print ( "Row#" + csvReader.getLineNumber () + " " ) ;
for ( String token : rowAsTokens ) {
System.out.print ( token + " " ) ;
}
System.out.println () ;
}
}
}
It gives the following output,
Row#1 aaaa bbbb cccc dddd
Row#2 one two three four