如何生成具有聚合输入文件的记录计数到一个输出文件的页脚?

时间:2018-03-21 16:28:30

标签: spring-batch

在Spring Batch中,我试图弄清楚如何生成包含所写记录数的页脚记录。我有两个输入文件,它们聚合成一个输出文件。请注意,我在单独的步骤中处理输入文件以过滤掉重复项。

1 个答案:

答案 0 :(得分:0)

我让它使用自定义FlatFileFooterCallback。

public class FooterCallback extends StepExecutionListenerSupport implements FlatFileFooterCallback {
    private StepExecution stepExecution;
    static private int totalCount = 0;

    public void writeFooter(Writer writer) throws IOException {
        int count = stepExecution.getWriteCount();
        if (stepExecution.getStepName().equals("step1")) {
            totalCount += count;
        }
        else {  // last step
            writer.write("T|" + (totalCount + count));
        }
    }

    @Override
    @BeforeStep
    public void beforeStep(StepExecution stepExecution) {
        this.stepExecution = stepExecution;
    }

}

然后向编写器添加了对setFooterCallback()的调用。

@Bean
public ItemWriter<OutputDetailRecord> firstFileItemWriter() {

    FlatFileItemWriter<OutputDetailRecord> itemWriter = new FlatFileItemWriter<>();

    HeaderWriterCallback headerWriterCallback = new HeaderWriterCallback();
    itemWriter.setHeaderCallback(headerWriterCallback);
    itemWriter.setFooterCallback(footerCallback);
    itemWriter.setResource(new FileSystemResource("/data/outputFile.txt"));

    DelimitedLineAggregator<OutputDetailRecord> delimitedLineAggregator =  new DelimitedLineAggregator<>();
    delimitedLineAggregator.setDelimiter("|");
    BeanWrapperFieldExtractor<OutputDetailRecord> extractor = new BeanWrapperFieldExtractor<>();
    extractor.setNames(new String[] {
            ...
            });

    delimitedLineAggregator.setFieldExtractor(extractor);
    itemWriter.setLineAggregator(delimitedLineAggregator);

    return itemWriter;
}

然后将listener()调用添加到步骤。

@Bean
public Step step1() {
    return stepBuilderFactory.get("step1")
            .<InputRecord1, OutputDetailRecord>chunk(10)
            .listener(footerCallback)
            .reader(firstFileItemReader())
            .processor(firstFileItemProcessor())
            .writer(firstFileItemWriter())
            .build();
}

工作的第二步看起来与上面的步骤类似。