gpt4 book ai didi

java - 无法使用 Apache Commons CSV 读取 CSV 文件 - IllegalArgumentException

转载 作者:行者123 更新时间:2023-12-03 09:02:37 26 4
gpt4 key购买 nike

我尝试使用 Apache Commons CSV 访问 CSV 文件(我从 eBay 的 MIP 服务器下载)中的数据,但遇到以下错误:

java.lang.IllegalArgumentException: Index for header 'Selected Category ID' is 4 but CSVRecord only has 1 values!

我不太确定原因,因为文件明确包含此索引。我的 CSV 文件如下所示:

enter image description here

我使用以下代码来访问文件:

CSVParser csvParser = null;

String selectedCategoryIDFieldName = "Selected Category ID";

try {
Reader reader = Files.newBufferedReader(Paths.get(CSVFile));
csvParser = new CSVParser(reader, CSVFormat.DEFAULT
.withHeader("SKU", "Locale", "Title", "Channel", selectedCategoryIDFieldName)
.withIgnoreHeaderCase()
.withTrim()
.withSkipHeaderRecord(true));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

if (csvParser != null) {
List<CSVRecord> csvRecords = csvParser.getRecords();
for (CSVRecord csvRecord : csvRecords) {
// Accessing values by the names assigned to each column

try {
long currentRecordNumber = csvRecord.getRecordNumber();
String SKU = csvRecord.get("SKU");
String categoryID = csvRecord.get(selectedCategoryIDFieldName);
// ^^ this line throws `IllegalArgumentException`


System.out.println("Current record number: " + currentRecordNumber);
System.out.println("SKU - > " + SKU);
System.out.println("categoyrID -> " + categoryID);


} catch (Exception e) {
e.printStackTrace();
}
}

我搜索了一下,发现最接近的问题是 here但这与我的问题无关,因为保存之前/之后的格式完全相同(换句话说,我没有看到其他用户问题中的格式有任何问题)。

更新:我刚刚在 for (CSVRecord csvRecord : csvRecords) 循环的第二次迭代中意识到此错误(该文件仅包含一条记录)。但是,我仍然不明白为什么如果 CSV 文件中只有一条记录,它会迭代两次。为什么它只按类别 ID 而不是按 SKU 列显示?

最佳答案

记录2中必须有一些空格。请在记事本或 Notepad++ 中打开该文件。

我不熟悉 apache commons csv 所以它可能不是最佳解决方案

for (CSVRecord csvRecord : csvRecords) {
if(csvRecord.size() >= csvParser.getHeaderMap.size()){ <--- add this if condition

关于java - 无法使用 Apache Commons CSV 读取 CSV 文件 - IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49263946/

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