Spring Batch-FlatFileItemReader用于不同的分隔文件 [英] Spring Batch - FlatFileItemReader for different delimited files

查看:153
本文介绍了Spring Batch-FlatFileItemReader用于不同的分隔文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的文件,一个用管道分隔符"|"分隔还有一个用逗号,".

I have two different files, one delimited by pipe separator "|" and one by comma ",".

我正在使用Spring Batch使用FlatFileItemReader处理这些文件.我不想有两个读者和两个作家的文件.我可以为这两个文件使用一个通用的FlatFileItemReader吗?

I am using Spring Batch to process these files using FlatFileItemReader. I dont want to have two readers and two writers for the files. Can I have somehow one generic FlatFileItemReader for both files?

文件映射到的对象也不同.

Also the objects to which the files will be mapped are different.

推荐答案

您可以注入DelimitedLineTokenizer,并可以根据需要设置定界符.您可以使用StepExecutionListener将其设为通用,并且需要覆盖beforeStep()方法.您将在StepExecution中设置定界符.当您解析,"分隔的文件时, stepExecution.getExecutionContext().putString("delimiter",,"); 当文件用"|"分隔时然后 stepExecution.getExecutionContext().putString("delimiter","|");

You can inject a DelimitedLineTokenizer and you can set the delimiter as per requirement. you can make it generic using StepExecutionListener and need to override the beforeStep() method. You will set delimiter in StepExecution. When you parse the file which are "," seperated then stepExecution.getExecutionContext().putString("delimiter", ","); and when file is seperated with "|" then stepExecution.getExecutionContext().putString("delimiter", "|");

但是您需要创建两个作业.需要相应地指定侦听器.

But you need to create two jobs. Need to specify listener accordingly.

您可以从春季中看到​​上述说明逻辑的示例批量使用步行技术
通用阅读器的代码:

You can see the example of above explain logic from Spring Batch on Walking Techie
Code for generic Reader:

@Bean
  @StepScope
  public FlatFileItemReader<Domain> reader(@Value("#{stepExecutionContext[delimiter]}") String delimiter) {
    FlatFileItemReader<Domain> reader = new FlatFileItemReader<>();
    reader.setResource(new ClassPathResource("sample-data.csv"));
    reader.setLineMapper(new DefaultLineMapper<Domain>() {{
      setLineTokenizer(new DelimitedLineTokenizer() {{
        setNames(new String[]{"id", "name"});
        setDelimiter(delimiter);
      }});
      setFieldSetMapper(new BeanWrapperFieldSetMapper<Domain>() {{
        setTargetType(Domain.class);
      }});
    }});
    return reader;
  }

您可以在

You can find the many examples on spring batch in spring boot from Spring Batch Tutorial. You will find here all kind of problems related to spring batch.

这篇关于Spring Batch-FlatFileItemReader用于不同的分隔文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆