从非结构化csv中读取SpringBatch

时间:2019-02-20 13:12:17

标签: csv spring-batch

我想从非结构化CSV文件中读取内容。这意味着它将每次具有不同的列类型。请帮忙。

1 个答案:

答案 0 :(得分:0)

是的,终于我自己找到了解决方案,我想与您分享。您可以编写LineMapper,并可以通过以下代码将非结构化标题(动态列)映射到每一行。请注意,我在作业调度时已读取标头,并将其作为JobParameter传递。

      @Bean
  @StepScope
  public FlatFileItemReader<Customer> csvReader(@Value("#{jobParameters[filepath]}") String filepath,
      @Value("#{jobParameters[header]}") String header,
      @Value("#{jobParameters[campaignId]}") String campaignId,
      @Value("#{jobParameters[_id]}") String _id) {

    FlatFileItemReader<Customer> flatFileItemReader = new FlatFileItemReader<>();
    flatFileItemReader.setResource(new FileSystemResource(filepath));
    flatFileItemReader.setName("customer-csv-file-reader");
    flatFileItemReader.setLinesToSkip(1);
    flatFileItemReader.setLineMapper(lineMapper(header,campaignId,_id));
    return flatFileItemReader;
  }




     @Bean
        @StepScope
        public LineMapper<Customer> lineMapper(@Value("#{jobParameters[header]}") String header,
            @Value("#{jobParameters[campaignId]}") String campaignId,
            @Value("#{jobParameters[_id]}") String _id) {
          return new LineMapper<Customer>() {

            public String[] headers = header.split(",");
            @Override
            public Customer mapLine(String line, int linenumber) throws Exception {


                Customer item = new Customer();
                String[] p = line.split(",");

                Map<String, String> properties = IntStream.range(0, headers.length).boxed()
                    .collect(Collectors.toMap(i -> headers[i], i -> p[i]));

                item.setCampaignId(new ObjectId(campaignId));
                item.setInviteId(new ObjectId(_id));
                item.setProperties(properties);
                return item;

            }
          };


      }