3

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

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

部门[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”,但可能会有所不同(更小或更大)。

4

7 回答 7

5

这应该可以解决问题:它基本上创建了 csv 文件的矩阵表示。

LinkedList<String[]> rows = new LinkedList<String[]>();
String dataRow = CSVFile.readLine();
// Read the number of the lines in .csv file 
// i = row of the .csv file
int i = 0; 
while ((datarow = CSVFile.readLine()) != null){
    i++;
    rows.addLast(dataRow.split(","));
}

String[][] csvMatrix = rows.toArray(new String[rows.size()][]);

在 csvMatrix[row][col]...

访问列时,通过执行以下操作断言您尝试访问的列号在范围内:

if(col < csvMatrix[row].length)
于 2012-11-17T19:02:13.307 回答
2

最好是使用ArraList<String>,如果你愿意convert as Array

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

于 2012-11-17T18:26:04.540 回答
2

您的代码有几个问题。异常是由于其中一行不包含足够的 ';' 分隔值。

您的代码的奇怪之处在于:

  for (String item:dataArray) {
    customer_id[i] = dataArray[0];

这仅仅意味着您重复相同的分配 15 次(只需删除 for (String item: ...))。

如果我是你,我会做以下事情:

创建一个类;像这样的东西:

public class Customer {
    private String customerId;
    private String companyName;

    // ...
    public static Customer create(final String... args) {
        if (args.length != 15) {
            return null; // or throw an exception
        }
        final Customer rv = new Customer();
        rv.setCustomerId(args[0]);
        rv.setCompanyName(args[1]);
        // ...
        return rv;
    }

    public String getCustomerId() {
        return customerId;
    }

    public void setCustomerId(final String customerId) {
        this.customerId = customerId;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(final String companyName) {
        this.companyName = companyName;
    }
}

使用集合(如上面的帖子中所建议):

    BufferedReader csv = new BufferedReader(new FileReader("Sub-Companies.csv"));
    List<Customer> customers = new LinkedList<Customer>();

    String data;
    while ((data = csv.readLine()) != null){
        Customer customer = Customer.create(data.split(";"));
        if (customer != null) {
            customers.add(customer);
        }
    }

如果您需要数组而不是集合,您可以执行以下操作:

Customer[] arr = customers.toArray(new Customer[customers.size()]);

使用库来读取文件...例如,您可以尝试http://opencsv.sourceforge.net/

于 2012-11-17T18:52:56.860 回答
1
department[i] = dataArray[2];  

例外意味着dataArray没有那么多元素(即 3)。
如果你想解析你的 CSV 文件,你可以通过指定任何缺失的元素必须有一个占位符来让你的生活更轻松。
我的意思是你可以有这样的记录:

a;b;c;d;e;f;g;h;j
其中每个字符都代表列的值,但是当缺少元素时,格式必须是:
a;;;;;f;g;h;j不是 a;f;g;h;j

这不是一个不寻常的期望,而是 CSV 文件中的规范,并且会大大简化您的代码,并且会避免数组索引异常,因为您的行将始终具有预期的列

于 2012-11-17T18:53:12.320 回答
1

使用数组列表:

public ArrayList<ArrayList<String>> parseDataFromCsvFile()
{
     ArrayList<ArrayList<String>> dataFromFile=new ArrayList<ArrayList<String>>();
     try{
         Scanner scanner=new Scanner(new FileReader("CSV_FILE_PATH"));
         scanner.useDelimiter(";");

         while(scanner.hasNext())
         {
            String dataInRow=scanner.nextLine();
            String []dataInRowArray=dataInRow.split(";");
            ArrayList<String> rowDataFromFile=new ArrayList<String>(Arrays.asList(dataInRowArray));
            dataFromFile.add(rowDataFromFile);
         }
         scanner.close();
     }catch (FileNotFoundException e){
        e.printStackTrace();
     }
     return dataFromFile;
}

调用方法(显示csv内容):

ArrayList<ArrayList<String>> csvFileData=parseDataFromCsvFile();

public void printCsvFileContent(ArrayList<ArrayList<String>> csvFileData)
{
    for(ArrayList<String> rowInFile:csvFileData)
    {
        System.out.println(rowInFile);
    }
}
于 2015-11-03T20:34:11.153 回答
0

如果您想使用 Gradle(而不是 Maven)将数据加载到参数化 JUnit 测试中,方法如下:

// import au.com.bytecode.opencsv.CSVReader;
@Parameters(name = "{0}: {1}: {2}")
public static Iterable<String[]> loadTestsFromFile2() {
    String separator = System.getProperty("file.separator");
    File tFile = loadGradleResource( System.getProperty("user.dir") + 
        separator +  "build" + separator + "resources" + separator +  "test" + 
            separator + "testdata2.csv" );
    List<String[]> rows = null;
    if ( tFile.exists() ) {
        CSVReader reader = null;
        try {
            reader = new CSVReader( new FileReader( tFile ), ',' );
            rows = reader.readAll();
        } catch (FileNotFoundException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }   
    }
    staticlogger.info("Finished loadTestsFromFile2()");
    return rows;
} 
于 2013-03-13T22:14:17.523 回答
0

请检查是否有java.util.StringTokenizer帮助

例子:

StringTokenizer tokenizer = new StringTokenizer(inputString, ";")

手册:StringTokenizer 文档

于 2015-08-15T05:45:03.917 回答