繁体   English   中英

未找到 Apache Commons CSV 映射

[英]Apache Commons CSV Mapping not found

我正在尝试使用 Apache Commons CSV 将具有某些标头的 CSV 文件读入 Java 对象。 但是,当我运行代码时,我得到以下异常:

Exception in thread "main" java.lang.IllegalArgumentException: Mapping for Color not found, expected one of [Color, Name, Price, House Cost, Rent, 1 House, 2 Houses, 3 Houses, 4 Houses, Hotel, Mortgage]
at org.apache.commons.csv.CSVRecord.get(CSVRecord.java:102)
at GameBoard.<init>(GameBoard.java:25)
at Game.main(Game.java:3)

有人可以解释异常来自哪里吗? 在我看来,Apache Commons 不知何故与我的输入不匹配。 我有什么问题还是有其他问题? 这是我的代码片段:

Reader in;
    Iterable<CSVRecord> records = null;
    try {
        in = new FileReader(new File(Objects.requireNonNull(getClass().getClassLoader().getResource("Properties.csv")).getFile()));
        records = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(in);
    } catch (IOException | NullPointerException e) {
        e.printStackTrace();
        System.exit(1);
    }
    for (CSVRecord record :
            records) {
        spaces.add(new Property(
                record.get("Color"),
                record.get("Name"),
                Integer.parseInt(record.get("Price")),

这是我的 csv 标题(对不起,一个被切断了,但这不是重点): csv 标头

谢谢!

我有同样的问题,只有当你引用第一列时才会发生,所有其他列名都在工作。 问题是,UTF-8 表示在前面添加了以下字符“0xEF,0xBB,0xBF”(参见Wikipedia page )。 这似乎是 commons-csv 的一个已知问题,但由于这是特定于应用程序的,因此无法修复( CSVFormat.EXCEL.parse 应该处理字节顺序标记)。

但是,有一个记录在案的解决方法:

http://commons.apache.org/proper/commons-csv/user-guide.html#Handling_Byte_Order_Marks

我遇到了同样奇怪的异常。 它实际上说“期待......”然后列出它说它找不到的字段 - 就像你的情况一样。

原因是我设置了错误的 CSVFormat:

CSVFormat csvFormat = CSVFormat.newFormat(';');

这意味着我的代码试图在一个实际上有逗号分隔符的文件中用分号分隔字段。

一旦我使用了 DEFAULT CSVFormat,一切都开始工作了。

CSVFormat csvFormat = CSVFormat.DEFAULT;

所以答案是您可能必须为您的文件正确设置 CSVFormat。

从 2.4.5 迁移到 Spring Boot 版本 2.6.7 会导致此错误。我必须将每个 csvRecord 转换为地图,然后再将其分配给我的 POJO,如下所示。

for (CSVRecord csvRecord : csvRecords) {

            Map<String, String> csvMap = csvRecord.toMap();

            Model newModel = new Model();
           model.setSomething(csvMap.get("your_item"));
        }

在此处输入图像描述

通过在 CSV 文件中提供不同的标题名称(例如xyz )或尝试通过调用csvRecord.get("x_z")来获取值,我也得到了相同的异常

我解决了更改标题名称xyz的问题。

try {
  fileReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  csvParser = new CSVParser(fileReader,
      CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
  Iterable<CSVRecord> csvRecords = csvParser.getRecords();
  CSVFormat csvFormat = CSVFormat.DEFAULT;
  for (CSVRecord csvRecord : csvRecords) {


} catch (Exception e) {
  System.out.println("Reading CSV Error!");
  e.printStackTrace();
} finally {
  try {
    fileReader.close();
    csvParser.close();
  } catch (IOException e) {
    System.out.println("Closing fileReader/csvParser Error!");
    e.printStackTrace();
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM