ArrayIndexOutOfBoundsException - 解析csv文件时

时间:2013-12-28 10:55:55

标签: java csv opencsv

我想转换一个csv文件。我的文件看起来像这样:

enter image description here

我使用opencsv库来解析我的csv。这是我解析文件的run方法:

public void run() throws Exception {


        CSVReader reader = new CSVReader(new FileReader(csvFile), ';');
        String [] nextLine;
        int i = -1;
        String fileName = "";
        String companyName = "";
        String currency = "";
        String writerPath;
        List<String> returnList = null;
        List<String> dateList = null;

        while ((nextLine = reader.readNext()) != null && i < 10) {
            String[] line = nextLine;
            System.out.println(line[0]);
            System.out.println(line);
            i++;

            //fileName of the String 
            if(!line[0].contains("NULL")) {
                fileName = line[0];
            }

            writerPath = "C:\\Users\\Desktop\\CSVOutput\\" + fileName + ".csv";
            //write csv file
            CSVWriter writer = new CSVWriter(new FileWriter(writerPath), ';');

            //write Header
            String[] entries = "Name;Date;TotalReturn;Currency".split(";");
            writer.writeNext(entries);

            //create Content

            //companyName of the String 
            if(!line[1].contains("Name")) {
                companyName = line[1];
                System.out.println(companyName);
            }

            //currency 
            if(!line[2].contains("CURRENCY")) {
                currency = line[2];
            }


            //total returns
            returnList = new ArrayList<String>();
            if(line[0].contains("NULL")) {
                for(int j = 3; j <= line.length; j++) {
                    returnList.add(line[j]); // EXCPETION COMES HERE!
                }
            }

            //"Name;Date;TotalReturn;Currency"
            List<String[]> data = new ArrayList<String[]>();
            for(int m = 0; m <= line.length; m++) {
                data.add(new String[] {companyName, "lolo", "hereComesTheDateLater", currency});
            }

            writer.writeAll(data);

            //close Writer
            writer.close();
        }
        System.out.println("Done");


    }

}

我正在

java.lang.ArrayIndexOutOfBoundsException: 3039
    at com.TransformCSV.main.ParseCSV.run(ParseCSV.java:78)
    at com.TransformCSV.main.ParseCSV.main(ParseCSV.java:20)

在这一行:returnList.add(line[j]);

为什么呢?有哪些方法可以解决这个问题?

我非常感谢你的回答!

2 个答案:

答案 0 :(得分:1)

您希望j < line.length <=。如果数组中有10个元素,那么索引10上没有项目 - 您只有0-9

进一步使用大量变量并分配它们不是解析CSV的首选方法。 Java是一种面向对象的语言。

使用Object代表每一行,并使用opencsv javabean API

绑定该行

答案 1 :(得分:1)

您正在解析文件直到文件<=的长度,而您必须使用<。它将访问文件,直到line.length - 1

替换为

for(int j = 3; j <line.length; j++) {
     returnList.add(line[j]); 
}
相关问题