如何在春季批处理中使用unknow列名和unknow列数读取csv?

问题描述 投票:0回答:1

我在步骤中遵循FlatFileItemReader配置:

@Bean
@StepScope
public FlatFileItemReader<RawInput> reader(FieldSetMapper<RawInput> fieldSetMapper, @Value("#{jobParameters['files.location']}") Resource resource) {
    var reader = new FlatFileItemReader<RawInput>();
    reader.setName("my-reader");
    reader.setResource(resource);
    var mapper = new DefaultLineMapper<RawInput>();
    mapper.setLineTokenizer(crmCsvLineTokenizer());
    mapper.setFieldSetMapper(fieldSetMapper);
    mapper.afterPropertiesSet();
    reader.setLineMapper(mapper);
    return reader;
}

RawInput包含1个字段,因此它使我可以读取单列的csv。现在需求有所变化,现在我必须能够读取任何行数的csv文件,因此我需要以某种方式传递数组而不是RawInput。 FlatFileItemReader是否可能,或者我应该更改实现?

spring csv spring-batch inputstream reader
1个回答
0
投票

有效:

    var reader = new FlatFileItemReader<List<String>>();
    reader.setName("reader");
    reader.setResource(resource);
    //line mapper
    var lineMapper = new DefaultLineMapper<List<String>>();        
    lineMapper.setLineTokenizer(new DelimitedLineTokenizer());
    lineMapper.setFieldSetMapper(myFieldSetMapper); // see implementation below
    lineMapper.afterPropertiesSet();

    reader.setLineMapper(lineMapper);
    return reader;


@Component
public class MyFieldSetMapper implements FieldSetMapper<List<String>> {

    @NonNull
    @Override
    public List<String> mapFieldSet(@NonNull FieldSet fieldSet) {
        return Arrays.stream(fieldSet.getValues())
                .map(StringUtils::lowerCase) // optional
                .map(StringUtils::trimToNull) // optional
                .collect(Collectors.toList());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.