繁体   English   中英

将CSV文件转换为2D Array Java

[英]Converting CSV file into 2D Array Java

我在将CSV文件转换为Java中的2D数组时遇到了一些麻烦。 我可能会走最长的路,但似乎无法弄清楚为什么我会出错。 每一行和每一列应该具有25个元素。 这是我的代码:

BufferedReader CSVFile = new BufferedReader(new FileReader(fileName));

String dataRow = CSVFile.readLine();
// Read first line.
// The while checks to see if the data is null. If 
// it is, we've hit the end of the file. If not, 
// process the data.

while (dataRow != null) {
    dataRow.split(",");
    list.add(dataRow);
    dataRow = CSVFile.readLine();

    // Read next line of data.
}
// Close the file once all data has been read.
CSVFile.close();

String[] tokens = null;
Object[] test = list.toArray();

String[] stringArray = Arrays.copyOf(test, test.length, String[].class); //copies the object array into a String array 

//splits the elements of the array up and stores them into token array

for (int a = 0; a < test.length; a++) {
    String temp = stringArray[a];
    tokens = temp.split(",");

}

//converts these String tokens into ints

int intarray[] = new int[tokens.length];

for (int i = 0; i < tokens.length; i++) {

    intarray[i] = Integer.parseInt(tokens[i]);

}

//attempts to create a 2d array out of a single dimension array
int array2d[][] = new int[10][3];

for (int i = 0; i < 25; i++) {
    for (int j = 0; j < 25; j++) {
        array2d[i][j] = intarray[(j * 25) + i];

    }
}

我相信错误是当ArrayList复制到第一个String数组时,但是我不确定。 该文件有25列25行。 我不断得到的错误是数组在索引25处超出范围。任何输入将不胜感激。 谢谢!

for (int a = 0; a < test.length; a++) {
    String temp = stringArray[a];
    tokens = temp.split(","); //< -- OLD VALUE REPLACED  WITH NEW SET OF TOKENS

}

tokens 将仅包含最后使用的字符串的标记, 而不是到目前为止看到的所有标记。 因此tokens.length == 25和访问tokens[25]ArrayOutOfBounds异常。

您应该进行以下更改

ArrayList<String> tokens = new ArrayList<String>();
...
tokens.addAll(Arrays.asList(temp.split(","))); 

从array创建ArrayList解释了如何将元素数组添加到arrayList。

顺便说一句,做自己的CSV解析可能不是您时间上最有效的使用方式(除非这是家庭作业)。 有很多很棒的库可以处理这个问题(opencsv,commons-lang3),它们处理诸如引用,空令牌,可配置的分隔符等问题。

这是commons-lang3的示例:

StrTokenizer tokenizer = StrTokenizer.getCSVInstance();

while (...) {
    tokenizer.reset(dataLine);
    String tokens[] = tokenizer.getTokenArray();
    ...
}

现在,您可以自由地专注于要对数据进行处理的实际逻辑,而不必进行繁琐的解析操作。

而且,如果您只想将令牌作为平面列表收集,请执行以下操作:

StrTokenizer tokenizer = StrTokenizer.getCSVInstance();
List<String> allTokens = new ArrayList<String>();
while (...) {
    tokenizer.reset(dataLine);
    allTokens.addAll(tokenizer.getTokenList());
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM