gpt4 book ai didi

java - 无法将 csv 文件中的数据读回数组

转载 作者:行者123 更新时间:2023-11-30 03:45:22 25 4
gpt4 key购买 nike

所以我有这段代码,但我无法从 csv 文件中检索数据并将它们放入数组中。

这是我的 CSV 文件中的内容

D001,55,Lab,ButchD002,22,Husky,BenD003,12,Maltese,JohnD004,34,GermanSheperd,JamesD005,76,Rot,Smith
public 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();

}

我刚刚开始学习编码,所以请耐心等待。谢谢

最佳答案

完成当前行的标记化后,您必须阅读下一行:

while (inStr != null) {
StringTokenizer dogTok = new StringTokenizer(inStr, ",");

while (dogTok.hasMoreTokens()) {
[...]
}
System.out.println("dog " + i + " is stored");
inStr = in.readLine();
i++; //replaced here
}

关于java - 无法将 csv 文件中的数据读回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25884381/

25 4 0