猿问

使用 FlatFileItemReader 读取元素列表

比方说,我有一个对象Engine,唯一的属性是brandName,然后我有一个 CSV 文件如下:


car_brand; bike_brand; airplane_brand; boat_brand

brand1;    brand2;     brand3;         brand4

brand5;    brand6;     brand7;         brand8

brand9;    brand10;    brand11;        brand12

我想要做的是读取 CSV 文件并为每一行创建一个列表。


由于我的项目是Spring批处理项目,我想使用Reader,但是怎么实现呢?


我尝试这样做:


@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;

}

通常你只用阅读器创建一个对象,我如何用阅读器创建列表?

我应该将方法类型更改为<List<Engine>>吗?


编辑: 我的问题不是如何制作列表的 Reader,而是如何制作列表的 FlatFileItemReader,重复的问题不是我需要的答案。


慕桂英546537
浏览 154回答 1
1回答

DIEA

您可以尝试以下操作:@BeanLineMapper<List<Engine>> lineMapper() {&nbsp; &nbsp; return new LineMapper<List<Engine>>() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public <List<Engine>> mapLine(String line, int lineNum) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String[] tokens = line.split(";");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (tokens.length < 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new DataIntegrityViolationException("Expecting at least one token in input line: " + line);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<Engine> data = new ArrayList<Engine>;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (String token : tokens) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data.add(Engine.of(token));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return data;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };}....FlatFileItemReader<List<Engine>> itemReader = new FlatFileItemReader<>();&nbsp; &nbsp; &nbsp; &nbsp; itemReader.setLineMapper(lineMapper);
随时随地看视频慕课网APP

相关分类

Java
我要回答