6

我正在尝试将 CSV 文件导入到可以在 Java 程序中使用的数组中。CSV 文件已成功导入,输出出现在终端上,但会引发错误:

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

在最后。此外,当我尝试调用数组中的元素时,它也显示相同的错误。我的代码如下:

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();
        }
    }   
}
4

4 回答 4

6

使用正确的 CSV 解析器比自己破解一个错误的解析器要好得多:http: //opencsv.sourceforge.net/

CSV 不是人们可能会想到的简单格式(是的,一行可以包含,不分隔两条数据的 a)。

于 2011-06-29T21:19:57.930 回答
2

这是上述问题的答案

 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();
    }

}

}

于 2012-09-10T11:43:52.613 回答
2

当有这么多优秀的图书馆时,我建议你不要重新发明轮子。尝试使用以下代码片段作为参考的uniVocity-parsers :

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
    // ......
}

如您所见,完成将 csv 数据解析为数组的任务只需要 2 行代码。此外,该库还提供了解析 CSV 数据的完整功能列表,具有出色的性能。

于 2015-05-15T23:03:15.357 回答
0

看起来像您的假设,文件中的一行始终包含三列并非对所有行都是正确的。将 for 循环语句替换为以下行以消除异常并查看它发生的原因:

for (int x=0; x<result.length; x++)
于 2011-06-29T21:26:10.640 回答