java - 将 Univocity 解析器与 Spring Batch 一起使用
问题描述
我正在尝试在 Spring Batch 中使用 Univocity Parsers。我面临的问题是如何整合它们。
Spring Batch Chunk Steps 遵循给定文件每一行的流程:
我需要在 ItemReader 中使用Univocity。它对输入文件(即 CSV 文件)的每一行执行该方法。我唯一做的就是使用 a来读取项目并将其直接转换为我的 Java 对象,返回一个已解析的 Bean,但我不想一次加载所有记录,以避免异常。我没有找到其他可以帮助我的东西。
我曾尝试使用此答案作为示例,但无法弄清楚一次返回一个项目的任何内容。
read()
BeanListProcessor
List
OutOfMemory
@Override
public Address read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
CsvParserSettings parserSettings = new CsvParserSettings();
//settings
CsvRoutines routines = new CsvRoutines(parserSettings);
for (Address address : routines.iterate(Address.class, input, "UTF-8")) {
/*
*here I need to return only the current object,
*the return of this method will be passed as an argument to a processor
*the next time this method is called it has to return the next one
*Could not figure out how to control what is the current.
*/
return ???:
}
return ???;
}
如何在我的 ItemReader 中使用 Univocity 一次读取一行,仍然使用 BeanProcessor 将我的行自动解析为我的 Java 对象?
解决方案
嗨,我是 lib 的作者。routines.iterate(Address.class, input, "UTF-8")
将返回一个Iterable<Address>
. 你可以从中得到一个Iterator<Address>
并将其保存Iterator<Address>
在内存中。
每次需要阅读下Address
,只需调用iterator.next()
。
我相信你的方法应该写成:
private Iterator<Address> iterator;
@Override
public Address read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
if(iterator == null){
CsvParserSettings parserSettings = new CsvParserSettings();
//settings
CsvRoutines routines = new CsvRoutines(parserSettings);
iterator = routines.iterate(Address.class, input, "UTF-8")).iterator();
}
if(iterator.hasNext()){
return iterator.next();
} else {
iterator = null;
}
return null;
}
希望这可以帮助。
推荐阅读
- php - zend Academic2 通知 ObjectHydrator
- java - 将字符串问题与 gson 解析的 JSON 数据进行比较
- mysql - MySQL表按最新日期从关系表中的值排序
- ionic-framework - 无需在浏览器中打开即可下载
- fabricjs - 调用 cavas.toDataUrl() 时抛出 DOMException 错误
- javascript - 如何使用 JavaScript 打印基本的圣诞树?
- python - 如何检查一列是否以pandas中的a或b结尾
- javascript - TypeError:在“对象”中找不到函数“排序”......但根据谷歌文档,所述对象应该是一个字符串
- javascript - 从浏览器缓存中卸载(删除)Javascript 模块
- c# - 如何从用户输入创建对象 - C#