gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:32:06 41 4
gpt4 key购买 nike

我正在使用以下依赖项来读取 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 文件中的总行数。我该怎么做?

最佳答案

阅读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));
}

关于java - 当 CSVParser 中有记录时,csvParser.getRecords() 返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52478637/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com