首页 > 解决方案 > 将 Univocity 解析器与 Spring Batch 一起使用

问题描述

我正在尝试在 Spring Batch 中使用 Univocity Parsers。我面临的问题是如何整合它们。

Spring Batch Chunk Steps 遵循给定文件每一行的流程: 我需要在 ItemReader 中使用Univocity。它对输入文件(即 CSV 文件)的每一行执行该方法。我唯一做的就是使用 a来读取项目并将其直接转换为我的 Java 对象,返回一个已解析的 Bean,但我不想一次加载所有记录,以避免异常。我没有找到其他可以帮助我的东西。 我曾尝试使用答案作为示例,但无法弄清楚一次返回一个项目的任何内容。
在此处输入图像描述
read()BeanListProcessorListOutOfMemory

@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 对象?

标签: javacsvparsingspring-batchunivocity

解决方案


嗨,我是 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;
}

希望这可以帮助。


推荐阅读