【发布时间】:2014-09-17 07:09:10
【问题描述】:
所以我有这段代码,但我无法从我的 csv 文件中检索数据并将它们放入数组中。
这是我的 CSV 文件中的内容
D001,55,实验室,布奇 D002,22,赫斯基,本 D003,12,马耳他语,约翰 D004,34,德国牧羊犬,詹姆斯 D005,76,Rot,Smithpublic static void CSVInputFile() throws IOException {
FileReader inFileReader;
BufferedReader in;
String inStr;
File myFile;
String dogID;
int size;
String breed;
String name;
myFile = new File("DogFile.csv");
inFileReader = new FileReader(myFile);
in = new BufferedReader(inFileReader);
inStr = in.readLine();
Dog[] NewReadDog = new Dog[5];
int i = 0;
while (inStr != null) {
StringTokenizer dogTok = new StringTokenizer(inStr, ",");
while (dogTok.hasMoreTokens()) {
dogID = dogTok.nextToken();
size = new Integer(dogTok.nextToken());
breed = dogTok.nextToken();
name = dogTok.nextToken();
NewReadDog[i] = new Dog(dogID, size, breed, name);
i++;
System.out.println("dog " + i + " is stored");
}
}
System.out.println("\nOutput Dogs from CSV FILE: ");
for (int count = 0; count < NewReadDog.length; count++) {
System.out.println(NewReadDog[count]);
}
in.close();
}
我刚刚开始学习编码,所以请多多包涵。 谢谢
【问题讨论】:
-
到底是什么问题?
-
您只是在阅读第一行。您应该将
in.readLine()放在一个循环中以读取所有行。 -
我不断收到这个 java.lang.ArrayIndexOutOfBoundsException: 5
-
您应该将
i = 0语句作为第一个while循环的第一行。这应该修复 ArrayIndexOutOfBoundsException。
标签: java arrays stringtokenizer