有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java csvParser。当CSVParser中有记录时,getRecords()返回空

我使用以下依赖项读取csv文件:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.5</version>
</dependency>

下面是我为读取csv文件而编写的代码:

Reader reader = Files.newBufferedReader(Paths.get(file.getPath()));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
for(CSVRecord csvRecord: csvParser) {
     System.out.println(csvRecord.get(0));
}

我可以通过上述方法读取csv文件中的每一行。但是csvParser。getRecords();返回空。我想要CSV文件中的总行数。我该怎么做


共 (4) 个答案

  1. # 1 楼答案

    我认为应该将其分配给数组列表,因为CSVParser会释放列表的内存

    CSVParser csvParser = CSVParser.parse(multipartFileStream, StandardCharsets.US_ASCII,
                    CSVFormat.EXCEL);
                    List<CSVRecord> listCsvRecord =  new ArrayList<>();
                    listCsvRecord.addAll(csvParser.getRecords());
                `
    
  2. # 2 楼答案

    仔细阅读getRecords() javadoc(重点是我的):

    The returned content starts at the current parse-position in the stream.

    你说:

    But csvParser.getRecords(); returns empty. I want the total number of lines in the CSV file. How can I do this?

    在迭代记录之前,必须调用csvParser.getRecords().size();。然后迭代它们

    例如:

    List<Records> records = csvParser.getRecords();
    int nbRecords = records.size();
    for(CSVRecord csvRecord: records) {
         System.out.println(csvRecord.get(0));
    }
    
  3. # 3 楼答案

    你可以做任何你能做的事,所以你应该能够

    StreamSupport.stream(csvParser.spliterator(), false).count()
    

    注意:它仍然会以这种方式(不必要地)分配记录

  4. # 4 楼答案

    univocity-parsers有一个内置的getInputDimension例程,可以为您提供这些信息——它应该比您尝试使用commons csv的速度至少快6倍

    这一行就可以做到:

    int lines = new CsvRoutines().getInputDimension(new File("/path/to/your.csv")).rowCount();
    

    希望这有帮助

    免责声明:我是这个图书馆的作者。它是开源和免费的(Apache 2.0许可证)