【问题标题】:Storing csv file contents into multiple arrays将 csv 文件内容存储到多个数组中
【发布时间】:2016-02-23 16:02:29
【问题描述】:

我有一个包含四列多行的 CSV 文件:

a,b,c,d /n

a,b,c,d /n

我成功读取了 .CSV 文件的内容并将它们放入 ArrayList。如何将每一列分成一个数组?我想要arrayA、ArrayB、ArrayC、ArrayD。

Scanner scan = new Scanner(new File(copyUri));
    ArrayList<String[]> records = new ArrayList<String[]>();
    String[] record = new String[2];
    while(scan.hasNext())
    {
        record = scan.nextLine().split(",");
        records.add(record);
    }

【问题讨论】:

    标签: java arrays csv


    【解决方案1】:

    在同一个循环中将它们分成数组。如果您不知道 csv 文件中的行数,我建议您使用 ArrayList。

    Scanner scan = new Scanner(new File(copyUri));
    ArrayList<String[]> records = new ArrayList<String[]>();
    String[] record = new String[2];
    ArrayList<String[]> a = new ArrayList<String[]>();
    ArrayList<String[]> b = new ArrayList<String[]>();
    ArrayList<String[]> c = new ArrayList<String[]>();
    ArrayList<String[]> d = new ArrayList<String[]>();
    
    while(scan.hasNext())
    {
        record = scan.nextLine().split(",");
        a.add(record[0]);
        b.add(record[1]);
        c.add(record[2]);
        d.add(record[3]);
        records.add(record);
    }
    

    另一种效率较低的解决方案是查找记录列表的大小,使用此大小创建数组并用您的数据填充它们。

    Scanner scan = new Scanner(new File(copyUri));
    ArrayList<String[]> records = new ArrayList<String[]>();
    String[] record = new String[2];
    while(scan.hasNext()) {
            record = scan.nextLine().split(",");
            records.add(record);
    }
    int rows = records.size();
    String[] a = new String[rows];
    String[] b = new String[rows];
    String[] c = new String[rows];
    String[] d = new String[rows];
    int j = 0;
    for (String[] temp : records) {
        a[j] = temp[0];
        b[j] = temp[1];
        c[j] = temp[2];
        d[j] = temp[3];
        j++;
    }
    

    我得到的第三个想法是用一定的大小(例如:5)初始化数组并随时调整数组的大小,但我认为这是效率最低的,因为每次你都必须将元素移动到新数组调整它的大小。

    【讨论】:

      【解决方案2】:

      使用univocity-parsers'ColumnProcessor 可靠地为您执行此操作:

      CsvParserSettings parserSettings = new CsvParserSettings();
      
      // To get the values of all columns, use a column processor
      ColumnProcessor rowProcessor = new ColumnProcessor();
      parserSettings.setRowProcessor(rowProcessor);
      
      CsvParser parser = new CsvParser(parserSettings);
      
      //This will kick in our column processor
      parser.parse(new FileReader(new File(copyUri)));
      
      //Finally, we can get the column values:
      Map<Integer, List<String>> columnValues = rowProcessor.getColumnValuesAsMapOfIndexes();
      

      比手工操作更干净、更快、更容易。这将处理具有不同列数的行等情况,并将null 添加到列表中,而不是向您抛出异常。

      披露:我是这个库的作者。它是开源免费的(Apache V2.0 许可)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-06
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        相关资源
        最近更新 更多