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

时间:2014-09-17 07:09:10

标签: java arrays stringtokenizer

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

这就是我在CSV文件中的内容

D001,55,Lab,Butch
D002,22,Husky,Ben
D003,12,Maltese,John
D004,34,GermanSheperd,James
D005,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();

}

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

1 个答案:

答案 0 :(得分:2)

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

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

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