简体   繁体   中英

Spring Batch - FlatFileItemWriter write to a file, close it, write to new file

So I have a custom class that extends FlatFileItemWriter that I am using to write a CSV file. Based on some condition I want to finish with my first file and then write to a new file. Is there a way to do this with FlatFileItemWriter?

Here is an example of my code:

@Override
public void write(List<? extends MyObject> items) throws Exception {
    ExecutionContext stepContext = this.stepExecution.getExecutionContext();
    int currentFileIncrememnt = (int) stepContext.get("currentFileIncrement");
    if(currentFileIncrement== fileIncrement) {
        super.write(items);
    }
    else {
        super.close();
        fileIncrement = currentFileIncrement;
        super.setHeaderCallback(determineHeaderCallback());
        super.setResource(new FileSystemResource("src/main/resources/" + fileIncrement+ ".csv"));
        super.setShouldDeleteIfExists(true);
        DelimitedLineAggregator<MyObject> delLineAgg = new DelimitedLineAggregator<>();
        delLineAgg.setDelimiter(",");
        BeanWrapperFieldExtractor<MyObject> fieldExtractor = new BeanWrapperFieldExtractor<>();
        fieldExtractor.setNames(new String[] {"id", "amount"});
        delLineAgg.setFieldExtractor(fieldExtractor);
        super.setLineAggregator(delLineAgg);
        super.write(items);
    }
}

I don t understand if you are using a custom writer or the spring one. If your using the custom (maybe extendig from spring one) you could use whatever you want by passing parameters through the processor, reader o mapper. If you want to use the Spring writer you should make isolated steps. Give more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM