【问题标题】:Use Univocity Parsers with Spring Batch将 Univocity 解析器与 Spring Batch 一起使用
【发布时间】:2020-01-03 03:33:44
【问题描述】:

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

Spring Batch Chunk Steps 遵循给定文件每一行的流程:

我需要在ItemReader 中使用 Univocity。它对输入文件(即 CSV 文件)的每一行执行read() 方法。我唯一做的就是使用BeanListProcessor 来读取项目并将其直接转换为我的Java 对象,返回已解析Bean 的List,但我不想一次加载所有记录,以避免OutOfMemory 异常.我没有找到其他可以帮助我的东西。

我曾尝试使用this 答案作为示例,但无法确定一次返回一项。

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

【问题讨论】:

    标签: java csv parsing spring-batch univocity


    【解决方案1】:

    您好,我是该库的作者。 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;
    }
    

    希望这会有所帮助。

    【讨论】:

    • 感谢您的回答!但是我怎样才能将它添加到阅读器?当read() 方法为处理器一次执行返回每一行(作为有问题的图像)?如果我使用您发布的代码,它将在返回之前遍历所有 te 对象,或者它将始终返回第一个。
    • 我已经更新了我的问题以说明我的尝试。
    猜你喜欢
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多