【问题标题】:reading in CSV file, arrayindex out of bounds error读取 CSV 文件,arrayindex 越界错误
【发布时间】:2016-03-08 05:07:20
【问题描述】:

我正在尝试读取一个 csv 文件,我创建了一个包含 9 个条目及其值的测试文件,但我的代码不会读到第二行,它说找不到该文件第二个关键,我已经尽可能多地尝试了它,有人可以帮助我吗?示例输入将包含类似这样的内容,但在一个 csv 文件中(所以每个都在一个新行中,我是新来的,还在学习在这里编辑文本): 迭戈,2 玛丽亚,2 阿曼多,5 肯,1

public static void main(String[] args) {

    HashMap<String, Integer> h = new HashMap<String, Integer>(511);


    try
    {
        Scanner readIn = new Scanner (new File ("test1.csv") );
        System.out.println("I'm here 1");


        while ( readIn.hasNext() )
        {               

            System.out.print(readIn.next());// for testing purposes only
            System.out.println("Check 2"); // for testing purposes only 


            String line = readIn.nextLine();
            String str[] = line.split(",");

            for (int i = 0; i < str.length ; i++)
            {
                String k = str[0];
                int v = Integer.parseInt(str[1]);
                h.insert(k , v);
            }

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

        }
        readIn.close();     
    }

    catch (ArrayIndexOutOfBoundsException ob)
    {
        System.out.println(" - The file wasn't found." );
    } 

    catch (FileNotFoundException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

【问题讨论】:

  • 请提供一些示例输入。
  • 我试过了,每个名字、数字对都换行了
  • 您能否也提供您看到的错误输出?我认为这条线 System.out.print(readIn.next());可能会丢掉你的代码。
  • 内容如下:我在这里 1 \n Diego, 2Check 2 \n Maria, 2 \n -找不到文件

标签: java csv file-io hashmap indexoutofboundsexception


【解决方案1】:

对 next() 或 nextLine() 的调用应该在调用 hasNext() 之前。但是在您的代码中,您已经检查了 hasNext() 在 while 循环中是否返回 true,然后调用了 next() 和nextLine() 在循环内。 你可以修改你的代码如下:

while ( readIn.hasNext() )
            {               

                String line = readIn.nextLine();
                String str[] = line.split(",");

                for (int i = 0; i < str.length ; i++)
                {
                    String k = str[0];
                    int v = Integer.parseInt(str[1]);
                    h.put(k , v);
                }

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

            }

【讨论】:

【解决方案2】:

您的 for 循环实际上并没有达到目的。您会注意到,您实际上从未在循环中引用 i。在 OP 的回答之前,我相信您试图拆分一个没有逗号的字符串,但是您的代码假设一个字符串会在那里,因此会出现越界异常。这与我告诉您println() 有问题的原因有关。

就您关于hasNext() 的问题而言,这是您知道可以从文件中读取另一行的唯一方法。如果你试图读到最后,你会遇到问题。

【讨论】:

    【解决方案3】:

    宁可自己编写代码来读取CSV 文件。我建议你使用像Apache Commons CSV 这样的标准库。提供了更多处理CSVTab separated file等的方法……

    import java.io.FileReader;
    import java.util.List;
    
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    
    public class SO35859431 {
        public static void main(String[] args) {
            String filePath = "D:\\user.csv";
            try {
                List<CSVRecord> listRecords = CSVFormat.DEFAULT.parse(new FileReader(filePath)).getRecords();
                for (CSVRecord csvRecord : listRecords) {
                    /* Get record using index/position */
                    System.out.println(csvRecord.get(0));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      首先HashMap类中没有这样的insert()方法,正确的是put(k, v)&在while循环中应该是hasNext()。下面是我的代码替代 BufferedReader。

      /* * 要更改此许可标头,请在项目属性中选择许可标头。 * 要更改此模板文件,请选择工具 |模板 * 并在编辑器中打开模板。 */ 包读取;

      import java.io.BufferedReader;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileNotFoundException;
      import java.io.FileReader;
      import java.io.IOException;
      import java.io.InputStreamReader;
      import java.util.HashMap;
      import java.util.Scanner;
      
      /**
       *
       * @author Isuru Rangana Jr
       */
      public class Read {
      
          /**
           * @param args the command line arguments
           */
          public static void main(String args[]) throws FileNotFoundException, IOException {
              HashMap<String, Integer> h = new HashMap<String, Integer>();
      
              try {
                  BufferedReader readIn = new BufferedReader(new FileReader(new File("test.csv")));
      
                  while (readIn.ready()) {
      
                      String line = readIn.readLine();
                      String str[] = line.split(",");
      
      
                      for (int i = 0; i < str.length; i++) {
                          String k = str[0];
                          int v = Integer.parseInt(str[1]);
                          h.put(k, v);
                      }
      
                      System.out.println(h.toString());
      
                  }
                  readIn.close();
              } catch (ArrayIndexOutOfBoundsException ob) {
                  System.out.println(" - The file wasn't found.");
              }
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-19
        • 2019-04-29
        • 2022-06-24
        • 1970-01-01
        • 2020-09-30
        相关资源
        最近更新 更多