Read CSV Line by Line
opencsv is a free and open source library for reading and writing
CSV files in Java. We need to have opencsv-2.3.jar or
later versions in classpath.
The following example shows reading a CSV file line by line using opencsv.
test1.csv
aaaa,bbbb,cccc,dddd
one,two,three,four
package com.bethecoder.tutorials.open_csv.tests;
import java.io.IOException;
import java.io.InputStreamReader;
import au.com.bytecode.opencsv.CSVReader;
public class ReadCSV {
/**
* @param args
* @throws IOException
*/
public static void main ( String [] args ) throws IOException {
/**
* Load CSV from classpath
*/
CSVReader csvReader = new CSVReader ( new InputStreamReader (
ReadCSV. class .getClassLoader () .getResourceAsStream ( "test1.csv" ))) ;
String [] rowAsTokens;
while (( rowAsTokens = csvReader.readNext ()) != null ) {
for ( String token : rowAsTokens ) {
System.out.print ( token + " " ) ;
}
System.out.println () ;
}
}
}
It gives the following output,
aaaa bbbb cccc dddd
one two three four