如何在没有 header 的情况下使用 opencsv 读取 csv 文件?
How to read csv file without header using opencsv?
我知道 header,但 header 是单独解析的。我正在使用带有注释的 pojo 并将其设置为类型。
我的代码如下所示:
CsvToBean<MyObject> bb = new CsvToBeanBuilder<MyObject>(reader)
.withSeparator(SEPERATOR)
.withIgnoreLeadingWhiteSpace(true)
.withType(MyObject.class)
.build();
当我迭代时,我得到了所有空值的 MyObject。 MyObject 是带有用列名注释的字段的 pojo。
有没有办法在 opencsv 中设置 headers?
CsvToBean
上有一个 MappingStrategy
。 ColumnPositionMappingStrategy
将允许您 link 按名称将列添加到 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();
正如我在上一条评论中提到的,我最终实施了自定义策略来解决我的问题。
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);
}
}
}
这就是所需要的。
我知道 header,但 header 是单独解析的。我正在使用带有注释的 pojo 并将其设置为类型。
我的代码如下所示:
CsvToBean<MyObject> bb = new CsvToBeanBuilder<MyObject>(reader)
.withSeparator(SEPERATOR)
.withIgnoreLeadingWhiteSpace(true)
.withType(MyObject.class)
.build();
当我迭代时,我得到了所有空值的 MyObject。 MyObject 是带有用列名注释的字段的 pojo。
有没有办法在 opencsv 中设置 headers?
CsvToBean
上有一个 MappingStrategy
。 ColumnPositionMappingStrategy
将允许您 link 按名称将列添加到 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();
正如我在上一条评论中提到的,我最终实施了自定义策略来解决我的问题。
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);
}
}
}
这就是所需要的。