春季批处理将船长项写入csv文件

时间:2019-03-07 13:40:42

标签: spring-batch

我想一步一步地在第一个csv文件中写入跳过行,而在第二个文件中写入处理器结果,但是不行!

我的代码:

        // => Step cecStep1
    @Bean
    public Step cecStep1(StepBuilderFactory stepBuilders) throws IOException {
        return stepBuilders.get("fileDecrypt")
                .<CSCivique, String>chunk(100)
                .reader(reader1())
                .processor(processor1FileDecrypt())
                .writer(writer1())
                .faultTolerant()
                .skip(Exception.class)
                .skipLimit(100)
                .listener(new MySkipListener())
                .build();
    }

// ################################### Step SkipListener ###### ###########################################

公共静态类MySkipListener实现了SkipListener {

        private BufferedWriter bw = null;

        public MySkipListener(File file) throws IOException {
            //this.fileWriter = new FileWriter(file);
            bw= new BufferedWriter(new FileWriter(file, true));
            System.out.println("MySkipListener =========> :"+file);
        }

        @Override
        public void onSkipInRead(Throwable throwable) {
            if (throwable instanceof FlatFileParseException) {
                FlatFileParseException flatFileParseException = (FlatFileParseException) throwable;
                System.out.println("onSkipInRead =========> :");
                try {
                        bw.write(flatFileParseException.getInput()+"; Vérifiez les colonnes !!");
                        bw.newLine();
                        bw.flush();
                  // fileWriter.close();
                } catch (IOException e) {
                    System.err.println("Unable to write skipped line to error file");
                }
            }
        }

        @Override
        public void onSkipInWrite(CSCivique item, Throwable t) {
            System.out.println("Item " + item + " was skipped due to: " + t.getMessage());
        }

        @Override
        public void onSkipInProcess(CSCivique item, Throwable t) {
            System.out.println("Item " + item + " was skipped due to: " + t.getMessage());
        }
    }           


    @Bean
    public FlatFileItemWriter<String> writer1() {
        return new FlatFileItemWriterBuilder<String>().name(greetingItemWriter)
                .resource(new FileSystemResource("target/test-outputs/greetings.csv"))
                .lineAggregator(new PassThroughLineAggregator<>()).build();
    }

Tankyou!

1 个答案:

答案 0 :(得分:0)

在处理器中,您可以:

  • 对无效项目抛出可跳过的异常,以便跳过侦听器拦截它们并将它们写入指定的文件
  • 让有效项目交给编写者,以便按照项目编写者中的配置对其进行编写

例如:

class MyItemProcessor implements ItemProcessor<Object, Object> {
    @Override
    public Object process(Object item) throws Exception {
        if (shouldBeSkipped(item)) {
            throw new MySkippableException();
        }
        // process item
        return item;
    }
}

希望这会有所帮助。