6

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();
        }
    }   
}
Roger Chen
  • 93
  • 1
  • 1
  • 6
  • 2
    Why are you using a hard coded constant in your for loop, instead of result size? – Perception Jun 29 '11 at 21:20
  • You can use existing Java CSV API for your needs : http://sourceforge.net/projects/csv4j/ or http://sourceforge.net/projects/javacsv/ for example. – Benoit Courtine Jun 29 '11 at 21:21
  • @Perception is right, are you sure you have 3 values after reading a line? – Marcelo Jun 29 '11 at 21:23
  • @Perception: I was doing that to temporarily test if I would continue to hit the exception, what is actually there should be result.length – Roger Chen Jun 29 '11 at 21:26

4 Answers4

6

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).

Mathias Schwarz
  • 7,099
  • 23
  • 28
  • How would you call the opencsv package into a Java program? I had tried implementing it before and don't seem to be getting it right somehow. Edit: Just found the /examples directory. – Roger Chen Jun 29 '11 at 21:23
  • One should be able to parse a simple csv file without using some "csv4j" library... – Andreas Dolk Jun 29 '11 at 21:27
  • Other readings on the Internet indicated that pulling CSV libraries might be easier. But yes, if you know how to easily parse a simple CSV file into an array that can be accessed by the rest of the Java program, I would greatly appreciate it! – Roger Chen Jun 29 '11 at 21:29
  • @Andreas_D: But why waste time on it? CSV parsing cannot be done by String.split since , is only a separator if not enclosed by "'s – Mathias Schwarz Jun 30 '11 at 05:19
  • @Roger: Nothing is going to be easier than just downloading the library and letting it do the work. The concrete problem in your code was that you iterated up to 3 even though the length was shorter than that, but you are far from having a CSV parser yet. – Mathias Schwarz Jun 30 '11 at 05:21
  • But OpenCSV is really simple. It will give you exactly the array you are looking for and you can iterate the rows exactly the way you are trying to. See the example here: http://opencsv.sourceforge.net/#how-to-read – Mathias Schwarz Jun 30 '11 at 05:22
  • For further information about why CSV is not as simple to parse as one might think: http://stackoverflow.com/a/416783/545127 – Raedwald Nov 14 '12 at 17:51
2

This is the answer for above Question

 public class Readline {

/**
 * @param args
 */
public static void main(String[] args) {
    String fileName = "C:/Users/karthikrao/Desktop/cvsFile.csv";
    ArrayList<Integer> margins = new ArrayList<Integer>();
    BufferedReader br;
    String line, token;
    int i;
    try {
        br = new BufferedReader(new FileReader(fileName));
        try {
            while ((line = br.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(line, ",\"");
                i = 0;
                while (st.hasMoreTokens()) {
                    token = st.nextToken();
                    if (margins.size() <= i) {
                        margins.add((Integer) token.length());
                    } else {
                        margins.set(
                                i,
                                Math.max(margins.get(i),
                                        (Integer) token.length()));
                    }
                    i++;
                }
            }

            br = new BufferedReader(new FileReader(fileName));
            while ((line = br.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(line, ",\"");
                i = 0;
                while (st.hasMoreTokens()) {
                    token = st.nextToken();
                    System.out.print(token);
                    for (int j = 0; j < margins.get(i) - token.length(); j++) {
                        System.out.print(" ");
                    }
                    System.out.print("|");
                    i++;
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

}

Rao's
  • 1,087
  • 8
  • 24
  • 45
2

I suggest you not re-inventing wheel when there are so many great libraries out there. Try the uniVocity-parsers with the following code snippt as reference:

public static void main(String[] args) throws FileNotFoundException {

    /**
     * ---------------------------------------
     * Read CSV rows into 2-dimensional array
     * ---------------------------------------
     */

    // 1st, creates a CSV parser with the configs
    CsvParser parser = new CsvParser(new CsvParserSettings());

    // 2nd, parses all rows from the CSV file into a 2-dimensional array
    List<String[]> resolvedData = parser.parseAll(new FileReader("/examples/example.csv"));

    // 3rd, process the 2-dimensional array with business logic
    // ......
}

As you can see, only 2 lines required to finish the task of parsing csv data into array. Additionally, the library provides full list of features in parsing CSV data with excellent performance.

xiaolei yu
  • 121
  • 3
0

Looks like your assumption, that a line in the file always has three columns isn't true for all lines. Replace the for loop statement with the following line to eliminate the exception and see, why it happend:

for (int x=0; x<result.length; x++)
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268