【问题标题】:Cant read back data from csv file into arrays无法将 csv 文件中的数据读回数组
【发布时间】:2014-09-17 07:09:10
【问题描述】:

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

这是我的 CSV 文件中的内容

D001,55,实验室,布奇 D002,22,赫斯基,本 D003,12,马耳他语,约翰 D004,34,德国牧羊犬,詹姆斯 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();

}

我刚刚开始学习编码,所以请多多包涵。 谢谢

【问题讨论】:

  • 到底是什么问题?
  • 您只是在阅读第一行。您应该将in.readLine() 放在一个循环中以读取所有行。
  • 我不断收到这个 java.lang.ArrayIndexOutOfBoundsException: 5
  • 您应该将i = 0 语句作为第一个while 循环的第一行。这应该修复 ArrayIndexOutOfBoundsException。

标签: java arrays stringtokenizer


【解决方案1】:

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

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

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

【讨论】:

  • ArrayIndexOutOfBounds 异常上升,因为你一直标记同一行,直到你达到数组的最大长度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 2012-09-13
  • 2021-11-30
  • 2011-05-16
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
相关资源
最近更新 更多