Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Data from CSV to Array in Java

I'm trying to import a CSV file into an array that I can use within a Java program. The CSV file has successfully imported itself and the output appears on Terminal but it throws the error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 
at CompareCSV.main(CompareCSV.java:19)

at the end. In addition, when I try to call up elements in the array, it also shows the same error. My code is below:

import java.io.*;
import java.util.*;

public class CompareCSV {

    public static void main(String[] args) {

        String fileName = "sampledata1.csv";
        try {
            BufferedReader br = new BufferedReader( new FileReader(fileName));
            String strLine = null;
            StringTokenizer st = null;
            int lineNumber = 0, tokenNumber = 0;

            while((fileName = br.readLine()) != null) {
                lineNumber++;
                String[] result = fileName.split(",");
                for (int x=0; x<result.length; x++) {
                    System.out.println(result[x]);
                }
            }
        }

        catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }   
}
like image 812
Roger Chen Avatar asked Jun 29 '11 21:06

Roger Chen


1 Answers

You are much better off using a proper CSV parser than hacking a faulty one up yourself: http://opencsv.sourceforge.net/

CSV is not the simple format one might be let to think (yes, a line can contain a , that does not separate two pieces of data).

like image 51
Mathias Schwarz Avatar answered Sep 19 '22 12:09

Mathias Schwarz