首页 > 解决方案 > 如何使用 Univocity 例程验证 CSV 标头?

问题描述

当我迭代 Java bean 时,我将 Univocity CSV 解析器与例程一起使用。有没有办法验证 CSV 标头?当我编辑 CSV 并添加无效标头时,它只是插入给定的 bean null 而没有任何错误。

型号类:

public class Customer {

@Format(formats ="yyyy-MM-dd")
@Parsed(field="C_DAY")
private Date day;

@Parsed(field="C_ID")
private Long id;

@Parsed(field="C_TYPE")
private String type;

@Format(formats ="yyyy-MM-dd")
@Parsed(field="C_ORIGIN_DATE")
private Date originDate;

@Format(formats ="yyyy-MM-dd")
@Parsed(field="C_REL_DATE")
private Date relDate;

@Parsed(field="C_LEGAL_ID")
private String legalId;

@Parsed(field="C_NAME")
private String name;}

解析器:

    @Autowired
private CustomerDAO dao;

public void parse(File file) throws IOException, SQLException, CustomerValidationException, ParseException {
    CsvParserSettings parserSettings = new CsvParserSettings();
    parserSettings.getFormat().setLineSeparator("\n");
    parserSettings.setHeaderExtractionEnabled(false);
    CsvRoutines routines = new CsvRoutines(parserSettings);
    List<Customer> customers = new ArrayList<>();
    java.util.Date stamp = getTimestamp(file);
    dao.checkTimestampDate(stamp);


    for (Customer customer : routines.iterate(Customer.class, file, "UTF-8")) {
        validateFileDateWithFileName(stamp, customer.getDay());
        validateCustomer(customer);
        customers.add(customer);
    }
    dao.save(customers);
}

标签: javacsvparsingunivocity

解决方案


图书馆的作者在这里。您可以设置BeanListProcessor一个属性以确保您的类中的所有标题都存在于输入中。strictHeaderValidationEnabledtrue

在这种情况下,您不能使用CsvRoutines,因为该类实现了使用自己的内部行处理器的便捷方法,因此您的将被忽略。试试这个代码:

    CsvParserSettings parserSettings = new CsvParserSettings();
    parserSettings.getFormat().setLineSeparator("\n");

    final List<Customer> customers = new ArrayList<>();
    final java.util.Date stamp = getTimestamp(file);
    dao.checkTimestampDate(stamp);

    parserSettings.setProcessor(new BeanProcessor<Customer>() {
        @Override
        public void beanProcessed(Customer customer, ParsingContext context) {
            validateFileDateWithFileName(stamp, customer.getDay());
            validateCustomer(customer);
            customers.add(customer);
        }
    });

    new CsvParser(parserSettings).parse(file, "UTF-8");

    dao.save(customers);

希望这可以帮助。


推荐阅读