Java:读取.csv文件并保存到数组中

我在尝试读取.csv文件并将每列保存到数组时遇到异常问题.
虽然,它可能看起来很长,但事实并非如此.我只有15个不同的阵列.

这是异常“线程中的异常”主行“java.lang.ArrayIndexOutOfBoundsException:2”中的行

department[i] = dataArray[2];

有什么我可以做的吗?

      BufferedReader CSVFile = 
            new BufferedReader(new FileReader("Sub-Companies.csv"));

      String dataRow = CSVFile.readLine();
      // Read the number of the lines in .csv file 
      // i = row of the .csv file
      int i = 0; 
      while (dataRow != null){
          i++;
          dataRow = CSVFile.readLine();

        }
      System.out.println(i);
      // Close the file once all data has been read.
      CSVFile.close();

      // End the printout with a blank line.
      System.out.println();

      // Save into arrays
      customer_id = new String[i];
      company_name = new String[i];
      department = new String[i];
      employer = new String[i];
      country = new String[i];
      zipcode = new String[i];
      address = new String[i];
      city = new String[i];
      smth1 = new String[i];
      smth2 = new String[i];
      phone_no1 = new String[i];
      phone_no2 = new String[i];
      email = new String[i];
      website = new String[i];
      customer_no = new String[i];

      // Read first line.
      // The while checks to see if the data is null. If 
      // it is, we've hit the end of the file. If not, 
      // process the data.
      int j;
      int counter;
      i = 0;

      // Read the file again to save the data into arrays
      BufferedReader CSV = 
            new BufferedReader(new FileReader("Sub-Companies.csv"));

      String data = CSV.readLine();

      while (data != null){
          String[] dataArray = data.split(";");
          for (String item:dataArray) {
            customer_id[i] = dataArray[0];
            company_name[i] = dataArray[1];
            department[i] = dataArray[2];
            employer[i] = dataArray[3];
            country[i] = dataArray[4];
            zipcode[i] = dataArray[5];
            address[i] = dataArray[6];
            city[i] = dataArray[7];
            smth1[i] = dataArray[8];
            smth2[i] = dataArray[9];
            phone_no1[i] = dataArray[10];
            phone_no2[i] = dataArray[11];
            email[i] = dataArray[12];
            website[i] = dataArray[13];
            customer_no[i] = dataArray[14];
            }


          //System.out.print(address[i] + "\n"); 
          data = CSV.readLine(); // Read next line of data.
          i++;
      }

先感谢您!

一些数据是“E3B3C5EB-B101-4C43-8E0C-ADFE76FC87FE;”Var Welk“Inh.Kar; NULL; NULL; DE; 16278; Rotr 3;Angermünde; NULL; NULL; 03331 / 354348-0; 0343331 / 364548-15 ; info@aalls.com; http://www.adss.com; ipo241“,但可能有所不同(更小或更大).

最佳答案
最好的是使用ArraList< String>如果你想转换为数组.

你的问题是你没有计算行数来创建数组大小但是你正在添加数据
基于split(“;”),因此数组长度不匹配,可用值从split(“;”)添加到数组中.

转载注明原文:Java:读取.csv文件并保存到数组中 - 代码日志