我正在尝试读取一个简单的 .CSV 文件并创建一个二维字符串数组。这是数组:
1,1,1,1,1,1
2,2,2,2,2,2
3,3,3,3,3,3
4,4,4,4,4,4
我的代码应该找到六列和四行,但它在第三列之后停止并移动到下一行,我无法弄清楚为什么会发生这种情况。
除此之外,即使它提前退出,它也会返回越界异常。
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
这是代码,后面是输出。
public String[][] ascToStringArray(String ascFileIn) {
String directory ="c:\\data\\"; // "\" is an illegal character
String[][] numbers= new String[4][6]; // 4 rows 6 columns
try{
BufferedReader Br = new BufferedReader(new FileReader(directory + ascFileIn));
String line;
int row = 0;
int col = 0;
//read each line of text file
while((line = Br.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line,",");
//Populating Columns
while (st.hasMoreTokens())
{
//get next token and store it in the array
numbers[row][col] = st.nextToken();
System.out.println(row + " " + col + " = " + st.nextToken());
col++;
}
row++;
}
//close the file
Br.close();
return numbers;
}
catch(IOException exc) {
System.out.println("Error reading file.");
return numbers;
}
}
这是输出:
0 0 = 1
0 1 = 1
0 2 = 1
1 3 = 2
1 4 = 2
1 5 = 2
如果有人能弄清楚为什么它会提前退出并抛出越界错误,无论我将数组设置多大,我都会非常感激。
最佳答案
您使用了 nextToken
两次。
numbers[row][col] = st.nextToken();<-1---
System.out.println(row + " " + col + " = " + st.nextToken());<--2--Skips element
但仅使用一个值,因此在一行中仅添加行的三个元素。
异常原因
在执行内部 while 循环后,您没有重置 col=0
,这会导致 col=6 的
因为数组中的 col size 是 6 表示 0 到 5,因此当 ArrayIndexOutOfBound
col=6
时会抛出异常。
关于Java StringTokenizer 超出 .CSV 文件范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24534505/