How to create a generic FlatFileItemReader to read CSV files with different headers?

后端 未结 1 750
悲哀的现实
悲哀的现实 2021-01-16 09:26

I\'m creating a job that will read and process different .csv files based on an input parameter. There are 3 different types of .csv files with different headers. I want to

1条回答
  •  梦毁少年i
    2021-01-16 09:57

    You wrote:

    A tasklet will first read the input parameter to decide which file type needs to be read.

    Because the tasklet or infoHolder knows about type of file you can implement the creation of specific FieldSetMapper instance.

    This is a demo example how it can be implemented:

    public class Solution {
        private InfoHolder infoHolder = new InfoHolder();
    
        @Bean
        public FlatFileItemReader reader()
        {
            FlatFileItemReader reader = new FlatFileItemReader();
            reader.setLinesToSkip(1);
    
            reader.setLineMapper(new DefaultLineMapper() {
                {
                    setLineTokenizer(infoHolder.getLineTokenizer());
                    setFieldSetMapper(infoHolder.getFieldSetMapper());
                }
            });
            return reader;
        }
    
        private class InfoHolder {
            DelimitedLineTokenizer getLineTokenizer() {
                return ;
            }
    
            FieldSetMapper getFieldSetMapper() {
                if (some condition for specific file POJO 1){
                    return new BeanWrapperFieldSetMapper() {
                        {
                            setTargetType(FileSpecificPOJO_1.class);
                        }
                    };
                } else if (some condition for specific file POJO 2){
                    return new BeanWrapperFieldSetMapper() {
                        {
                            setTargetType(FileSpecificPOJO_2.class);
                        }
                    };
                }
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题