如何使用opencsv读取没有标头的csv文件?

问题描述 投票:1回答:2

我知道标题,但标题是单独解析的。我正在使用带注释的pojo并将其设置为类型。

我的代码看起来像这样:

 CsvToBean<MyObject> bb = new CsvToBeanBuilder<MyObject>(reader)
                .withSeparator(SEPERATOR)
                .withIgnoreLeadingWhiteSpace(true)
                .withType(MyObject.class)
                .build();

当我迭代时,我得到所有空值的MyObject。 MyObject是带有用列名注释的字段的pojo。

有没有办法在opencsv中设置标头?

java csv parsing opencsv
2个回答
0
投票

MappingStrategy上有一个CsvToBeanColumnPositionMappingStrategy将允许您按名称将列链接到bean属性。

例如:

    CsvToBean<MyObject> bb = new CsvToBeanBuilder<MyObject>(reader)
            .withSeparator(SEPERATOR)
            .withIgnoreLeadingWhiteSpace(true)
            .withType(MyObject.class)
            .build();

    ColumnPositionMappingStrategy<MyObject> mappingStrategy = new ColumnPositionMappingStrategy<>();
    mappingStrategy.setType(MyObject.class);
    mappingStrategy.setColumnMapping("property1", "property2");
    bb.setMappingStrategy(mappingStrategy);

    bb.parse();

0
投票

正如我在上一篇评论中提到的,我最终实施了一个自定义策略来解决我的问题。

public class BlahMappingStrategy extends HeaderColumnNameMappingStrategy {
List<String> headerList;

public BlahMappingStrategy(List<String> headerList) {
    this.headerList = headerList;
}

@Override
public void captureHeader(CSVReader reader) throws IOException, CsvRequiredFieldEmptyException {
    if (this.type == null) {
        throw new IllegalStateException(ResourceBundle.getBundle("opencsv", this.errorLocale).getString("type.unset"));
    } else {
        String [] header = headerList.toArray(new String[headerList.size()]);
        this.headerIndex.initializeHeaderIndex(header);
    }
}

}

这就是所需要的一切。

© www.soinside.com 2019 - 2024. All rights reserved.