Reputation: 684
Let's say, I have an object Engine, the only attribute is brandName, I then have a CSV file as below:
car_brand; bike_brand; airplane_brand; boat_brand
brand1; brand2; brand3; brand4
brand5; brand6; brand7; brand8
brand9; brand10; brand11; brand12
What I want to do, is reading the CSV file and creating a List for each row.
Since my project is a Spring batch project, I want to use a Reader, but how can I do it?
I tried to do:
@Bean
public FlatFileItemReader<Engine> reader() {
FlatFileItemReader<Engine> reader = new FlatFileItemReader<Project>();
reader.setResource(new ClassPathResource("file.csv"));
reader.setLinesToSkip(1);
reader.setLineMapper(new DefaultLineMapper<Project>() {
{
setLineTokenizer(new DelimitedLineTokenizer() {
{
setNames(***);
}
});
setFieldSetMapper(new BeanWrapperFieldSetMapper<Project>() {
{
setTargetType(Engine.class);
}
});
}
});
return reader;
}
Usually you create only one object with the reader, how can I create List with the Reader?
Should I change the method type to < List< Engine>>?
EDIT: My question is not how to make a Reader of a List, but how to make a FlatFileItemReader of a List, the duplicate question is not the answer I needed.
Upvotes: 1
Views: 2961
Reputation: 3572
You could try following:
@Bean
LineMapper<List<Engine>> lineMapper() {
return new LineMapper<List<Engine>>() {
@Override
public <List<Engine>> mapLine(String line, int lineNum) throws Exception {
String[] tokens = line.split(";");
if (tokens.length < 1) {
throw new DataIntegrityViolationException("Expecting at least one token in input line: " + line);
}
List<Engine> data = new ArrayList<Engine>;
for (String token : tokens) {
data.add(Engine.of(token));
}
return data;
}
};
}
....
FlatFileItemReader<List<Engine>> itemReader = new FlatFileItemReader<>();
itemReader.setLineMapper(lineMapper);
Upvotes: 1