如何在 spring 批处理中使用未知列名和未知列数读取 csv?
How to read csv with unknow column names and with unknow column count using in spring batch?
我的步骤遵循 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 或者我应该更改实现?
有效:
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());
}
}
我的步骤遵循 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 或者我应该更改实现?
有效:
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());
}
}