【问题标题】:Array Index out of bounds when reading from CSV file从 CSV 文件读取时数组索引超出范围
【发布时间】:2015-04-19 13:44:15
【问题描述】:

我正在尝试使用 BufferedReader 读取 CSV 文件,但由于某种原因,我在 7 行后出现了越界异常。我在另一个 CSV 文件(30 行)上尝试了这个精确的算法,效果很好。 Here 是有问题的 CSV 文件。

    String spellPath = "file path is here";

    FileReader y = new FileReader(spellPath);
    BufferedReader x = new BufferedReader(y);
    ArrayList<Card> ArrayList = new ArrayList<Card>( );   //dynamic data type

    for( String p = x.readLine(); p != null ; p = x.readLine()){

        String [] stArray = p.split(",");
        ArrayList.add(new Card( stArray[1], stArray[2])); //new card with name and desc only

    }

    System.out.println(ArrayList.toString());

是文件问题还是算法问题?

【问题讨论】:

  • 使用这种类型的循环while((String s = br.readLine()) != null)而不是for循环
  • 至少有一行没有逗号。看起来您的某一行中间有一个换行符。

标签: java csv exception buffered reader


【解决方案1】:

这里抛出错误

String [] stArray = p.split(",");
 ArrayList.add(new Card( stArray[1], stArray[2]));

添加此条件并检查

String [] stArray = p.split(",");
ArrayList.add(new Card( stArray[0], stArray[1]));

【讨论】:

  • 答案是生命权,因为它设定了正确的方向。
【解决方案2】:

试试这个。

while(x.readLine() != null){
---`enter code here`
}

【讨论】:

    【解决方案3】:

    您在循环中调用了x.readLine()两次。因此,您在阅读时会跳行。

    更好的方法是使用 CSVReader 而不是缓冲阅读器。

    CSVReader reader = new CSVReader(new FileReader(fName), ',','"','|');
        List content = reader.readAll();//do not use this if CSV file is large
        String[] row = null;
    
        for (Object object : content) {
            row = (String[]) object;
            row = Arrays.toString(row).split(",");
            //now you have a row array with length equal to number of columns
        }
    

    这里是获取 CSVReader 的链接 - CSVReader Download

    【讨论】:

      【解决方案4】:
      while((String p = x.readLine()) != null){
      
          String [] stArray = p.split(",");
          ArrayList.add(new Card( stArray[0], stArray[1])); //new card with name and desc only
      
      }
      
      System.out.println(ArrayList.toString());
      

      这应该可行

      【讨论】:

        【解决方案5】:

        有一句话“你场上每有一张魔法卡,攻击力和防御力都增加 500”。不包含任何,。所以stArray[] 的长度为 1。

        其他:Java 数组是零基数。

        for( String p = x.readLine(); p != null ; p = x.readLine()){ 应该是 while ((String p = x.readLine())!= null ){

        【讨论】:

          【解决方案6】:

          您的问题是连续两次调用 p=x.readLine()

          for( String p = x.readLine(); p != null ; p = x.readLine()){
              ...
          }
          

          因此,读取 2 行,仅检查 1 行是否为空

          你需要把循环改成

          while (true) {
              String p= x.readLine();
              if (p == null) break;
          
              ...
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-12-11
            • 2015-10-23
            • 1970-01-01
            • 2020-03-28
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多