java - 如何使用 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);
}
解决方案
图书馆的作者在这里。您可以设置BeanListProcessor
一个属性以确保您的类中的所有标题都存在于输入中。strictHeaderValidationEnabled
true
在这种情况下,您不能使用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);
希望这可以帮助。
推荐阅读
- java - 使用php和mysql数据库登录android应用程序
- here-api - 这里 Map JS 集群标记删除选项
- swift - swift - 为什么全局静态变量不是初始化?
- node.js - 无法使用 dgraph-orm 查询嵌套关系
- sql - SQL Server 将 MMM-YYYY 转换为真实日期
- vmware-workstation - vmware工作站开机虚拟机问题
- fullpage.js - 添加新部分时,Fullpage.js 不起作用
- python - Pandas 中的条件运行总和仅适用于所有以前的值
- unity3d - 如何在 Unity3D proyecto26 库中使用 graphql?
- python - 使用 google colab 时无法从 pandas 导入数据框