将CSV文件导入2D字符串数组

时间:2013-05-28 04:44:30

标签: java arrays csv

我必须将文本文件读入2d数组。

我遇到的唯一问题是数组的宽度各不相同,最大大小为9列。 我不知道会有多少行。

有些行例如有6列,有些行有9列。

这是我的CSV文件的一小部分:

1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
1910,Newtown,Souths,Newtown,Wests,Y,4,4,14000
1911,Easts,Glebe,Glebe,Balmain,Y,11,8,20000
1912,Easts,Glebe,Easts,Wests,N
1913,Easts,Newtown,Easts,Wests,N

这是我到目前为止的代码

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

public class ass2 {

    public static void main(String[] args) throws IOException {
        readData();

    }

    public static void readData() throws IOException{
        BufferedReader dataBR = new BufferedReader(new FileReader(new File("nrldata.txt")));
        String line = "";

        ArrayList<String[]> dataArr = new ArrayList<String[]>(); //An ArrayList is used because I don't know how many records are in the file.

        while ((line = dataBR.readLine()) != null) { // Read a single line from the file until there are no more lines to read

            String[] club = new String[9]; // Each club has 3 fields, so we need room for the 3 tokens.

            for (int i = 0; i < 9; i++) { // For each token in the line that we've read:
                String[] value = line.split(",", 9);                
                club[i] = value[i]; // Place the token into the 'i'th "column"
            }

            dataArr.add(club); // Add the "club" info to the list of clubs.
        }

        for (int i = 0; i < dataArr.size(); i++) {
            for (int x = 0; x < dataArr.get(i).length; x++) {
                System.out.printf("dataArr[%d][%d]: ", i, x);
                System.out.println(dataArr.get(i)[x]);
            }
        }
    }

我得到的错误是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at ass2.readData(ass2.java:23)
at ass2.main(ass2.java:7)

有人可以帮忙:'(

谢谢!

4 个答案:

答案 0 :(得分:11)

您可以使用OpenCSV来阅读CSV文件。

// Read all
CSVReader csvReader = new CSVReader(new FileReader(new File("nrldata.txt")));
List<String[]> list = csvReader.readAll();

// Convert to 2D array
String[][] dataArr = new String[list.size()][];
dataArr = list.toArray(dataArr);

答案 1 :(得分:2)

问题在于你的内循环。您正在尝试访问value的9个元素,无论该行上有多少个值。首先,您应该将赋值移动到value,使其位于内循环之前。然后,您需要将循环迭代限制为最小值9和value的长度:

String[] value = line.split(",", 9);                
int n = Math.min(value.length, data.length);
for (int i = 0; i < n; i++) { // For each token in the line that we've read:
    data[i] = value[i]; // Place the token into the 'i'th "column"
}

请注意data的尾随元素为null

答案 2 :(得分:1)

您收到错误,因为您尝试访问仅包含6的行上的第7个令牌(索引6)。替换为:

for (int i = 0; i < 9; i++) { // For each token in the line that we've read:
    String[] value = line.split(",", 9);                
    data[i] = value[i]; // Place the token into the 'i'th "column"
}

用这个:

String[] value = line.spkit(",", 9);   // Split the line into max. 9 tokens
for (int i = 0; i < value.length; i++) {
    data[i] = value[i];   // Add each token to data[]
}

事实上,你可以用这个单行代替整个while-loop身体:

dataArr.add(Arrays.copyOf(line.split(",", 9), 9));

另请参阅此 short demo

答案 3 :(得分:0)

您可以使用ArrayList的{​​{1}}代替数组。由于List是动态可扩展的,因此您无需考虑它的大小。

List

List<List<String>> dataArr = new ArrayList<List<String>>();