是否可以使用BeanListProcessor计算CSV文件中的列数?我的目标是验证标头数是否等于CSV文件中的值数.
我试过这个解决方案:what is the fastest way to get dimensions of a csv file in java
但这只适用于RowProcessor,而我正在使用BeanListProcessor;
BeanListProcessor<SomeObject> rowProcessor = new BeanListProcessor<SomeObject>(SomeObject.class);
我尝试在BeanProcess中重写RowProcessor的方法,但它被声明为final.
有没有其他方法可以用univocity验证CSV文件?
最佳答案 您始终可以包装行处理器以实现任何自定义逻辑来管理输入的处理方式:
public class MyRowProcessor<T> implements RowProcessor {
private final BeanListProcessor<T> wrappedProcessor;
public MyRowProcessor(Class<T> beanType) {
wrappedProcessor = new BeanListProcessor<T>(beanType);
}
@Override
public void processStarted(ParsingContext context) {
wrappedProcessor.processStarted(context);
}
@Override
public void rowProcessed(String[] row, ParsingContext context) {
//validate the input row here
if(row.length != context.headers().length){
return; // Example: I'm skipping the row if the number of columns doesn't match number of headers
}
//send the row to the wrapped processor (or skip, or do anything you want)
wrappedProcessor.rowProcessed(row, context);
}
@Override
public void processEnded(ParsingContext context) {
wrappedProcessor.processEnded(context);
}
public List<T> getBeans() {
return wrappedProcessor.getBeans();
}
}
您现在要做的就是使用自定义实现:
MyRowProcessor<SomeObject> processor = new MyRowProcessor<SomeObject>(SomeObject.class);
settings.setRowProcessor(processor);
settings.setHeaderExtractionEnabled(true);
CsvParser parser = new CsvParser(settings);
parser.parse(new File("/path/to/file"));
List<TestBean> beans = processor.getBeans();