我需要读取CSV文件中特定列名的值
我明白我需要以这种方式静态声明所有列名:
lineTokenizer.setNames(new String[]{"name1","name2","name3"});
例如,如果我只想读取列名称2的值,就这样做:
public class PushItemFieldSetMapper implements FieldSetMapper<MyObject > {
@Override
public MyObject mapFieldSet(FieldSet fieldSet) throws BindException {
MyObject myobject= new MyObject ();
pushItemDTO.setName2(fieldSet.readString("name2"));
return myobject;
}
}
但明天我可能会得到不同的CSV文件:
name7,NAME2 name9,name19
修改
之后需要重新编译我的代码lineTokenizer.setNames...
我总是希望从特定列名称(在本例中为name2)中检索值,而不是关心其他列名称。如何在不静态声明我的列名称的情况下动态执行此操作?
正如所建议我尝试做这样的事情:
public FlatFileItemReader<PushItemDTO> reader() {
FlatFileItemReader<PushItemDTO> itemReader = new FlatFileItemReader<PushItemDTO>();
itemReader.setSkippedLinesCallback(new LineCallbackHandler() {
@Override
public void handleLine(String line) {
head=line;
}
});
itemReader.setLineMapper(lineMapper());
itemReader.setLinesToSkip(1);
itemReader.setResource(new FileSystemResource("c:/newfile.txt"));
return itemReader;
}
@Bean
public LineMapper<PushItemDTO> lineMapper(String head) {
DefaultLineMapper<PushItemDTO> lineMapper = new DefaultLineMapper<PushItemDTO>();
DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();
lineTokenizer.setDelimiter(",");
lineTokenizer.setStrict(true);
//need to inject into here somehow the head on each execution
lineTokenizer.setNames(
});
//need to inject into here somehow the head on each execution
BeanWrapperFieldSetMapper<PushItemDTO> fieldSetMapper = new BeanWrapperFieldSetMapper<PushItemDTO>();
fieldSetMapper.setTargetType(PushItemDTO.class);
lineMapper.setLineTokenizer(lineTokenizer);
lineMapper.setFieldSetMapper(new PushItemFieldSetMapper());
但是我如何将头部传递给linemapper()?