Java 解析CSV:使用Univocity和bean processor计算列数

Java 解析CSV:使用Univocity和bean processor计算列数,java,csv,Java,Csv,是否可以使用BeanListProcessor计算CSV文件中的列数?我的目标是验证头的数量是否等于CSV文件中的值的数量 我尝试过这个解决方案: 但这只适用于RowProcessor,我使用的是BeanListProcessor BeanListProcessor<SomeObject> rowProcessor = new BeanListProcessor<SomeObject>(SomeObject.class); BeanListProcessor rowPr

是否可以使用BeanListProcessor计算CSV文件中的列数?我的目标是验证头的数量是否等于CSV文件中的值的数量

我尝试过这个解决方案:

但这只适用于RowProcessor,我使用的是BeanListProcessor

BeanListProcessor<SomeObject> rowProcessor = new BeanListProcessor<SomeObject>(SomeObject.class);
BeanListProcessor rowProcessor=新的BeanListProcessor(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实现RowProcessor{
专用最终BeanListProcessor wrappedProcessor;
公共MyRowProcessor(类beanType){
wrappedProcessor=新的BeanListProcessor(beanType);
}
@凌驾
已启动公共void进程(ParsingContext上下文){
wrappedProcessor.ProcessStart(上下文);
}
@凌驾
public void rowProcessed(字符串[]行,ParsingContext上下文){
//在此处验证输入行
if(row.length!=context.headers().length){
return;//示例:如果列数与标题数不匹配,则跳过该行
}
//将行发送到包装处理器(或跳过,或执行任何您想要的操作)
wrappedProcessor.rowProcessed(行,上下文);
}
@凌驾
public void processEnded(ParsingContext上下文){
wrappedProcessor.processEnded(上下文);
}
公共列表getBeans(){
返回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();
MyRowProcessor=新的MyRowProcessor(SomeObject.class);
设置。setRowProcessor(处理器);
设置。setHeaderExtractionEnabled(真);
CsvParser parser=新的CsvParser(设置);
parser.parse(新文件(“/path/to/File”);
List bean=processor.getBeans();

谢谢杰罗尼莫!让它工作起来。顺便说一句,很棒的图书馆。