Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA - import CSV to ArrayList

I'm trying import CSV file to Arraylist using StringTokenizer:

public class Test
{
  public static void main(String [] args)
  {
    List<ImportedXls> datalist = new ArrayList<ImportedXls>();

    try
    {
      FileReader fr = new FileReader("c:\\temp.csv");
      BufferedReader br = new BufferedReader(fr);
      String stringRead = br.readLine();

      while( stringRead != null )
      {
        StringTokenizer st = new StringTokenizer(stringRead, ",");
        String docNumber = st.nextToken( );
        String note = st.nextToken( );  /** PROBLEM */
        String index = st.nextToken( ); /** PROBLEM */

        ImportedXls temp = new ImportedXls(docNumber, note, index);
        datalist.add(temp);

        // read the next line
        stringRead = br.readLine();
      }
      br.close( );
    }
    catch(IOException ioe){...}

    for (ImportedXls item : datalist) {
      System.out.println(item.getDocNumber());
    }
  }
}

I don't understand how the nextToken works, because if I keep the initialize three variables (docNumber, note and index) as nextToken(), it fails on:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(Unknown Source)
    at _test.Test.main(Test.java:32)

If I keep docNumber only, it works. Could you help me?

like image 347
gaffcz Avatar asked Oct 10 '11 12:10

gaffcz


2 Answers

It seems that some of the rows of your input file have less then 3 comma separated fields.You should always check if tokenizer has more tokens (StringTokenizer.hasMoreTokens), unless you are are 100% sure your input is correct.

CORRECT parsing of CSV files is not so trivial task. Why not to use a library that can do it very well - http://opencsv.sourceforge.net/ ?

like image 178
aav Avatar answered Oct 05 '22 01:10

aav


Seems like your code is getting to a line that the Tokenizer is only breaking up into 1 part instead of 3. Is it possible to have lines with missing data? If so, you need to handle this.

like image 39
John B Avatar answered Oct 05 '22 01:10

John B