New Output file for each Item passed into FlatFileItemWriter

北城余情 提交于 2019-12-13 07:00:38

问题


I have the following domain object. This is the object being passed from my processor to my writer.

public class DivisionIdPromoCompStartDtEndDtGrouping {

    private int divisionId;
    private Date rpmPromoCompDetailStartDate;
    private Date rpmPromoCompDetailEndDate;
    private List<MasterList> detailRecords = new ArrayList<MasterList>();

I would like a new file per DivisionIdPromoCompStartDtEndDtGrouping. each file would have a line for each of the detailRecords in the list. The output files would be of the same format just logically separated based on data (divisionId,rpmPromoCompDetailStartDate and rpmPromoCompDetailEndDate).

How can I create an FlatFileItemWriter to output a new file for each DivisionIdPromoCompStartDtEndDtGrouping with the content detailRecords?

I think the answer might be a compositeItemWriter. Is that right? Could someone help me with an example of this.

thanks in advance


回答1:


You're close. Instead of just a CompositeItemWriter, use a ClassifierCompositeItemWriter. This coupled with a Classifier implementation that will choose a writer by grouping will allow you to have one file per group. You can read more about this ItemReader in the javadoc here: http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/item/support/ClassifierCompositeItemWriter.html




回答2:


No, the answer is not a composite writer. A composite writer simple forwards all items it receives to all defined childwriters.

The problem with FlatFileItemWriter is, that you you have to open and to close it, which is handled by the Framwork itself.

A simple approach would be to implement your own writer and use a FlatFileWriter in its write method.

public class MyWriter implements ItemWriter<..>{

  public void write(List<..> items) {
    for (.. item:items) {
       FlatFileItemWriter fileWriter = new FlatFileItemWriter();
       fileWriter.setResource(...); // unique FileName
       fileWriter.setLineAggregator(...);
       fileWriter.... ; // do other settings if necessary
       fileWriter.afterPropertiesSet();

       fileWriter.open(new ExecutionContext());

       fileWriter.write(Collections.singleList(item));

       fileWriter.close();
     }      
  } 
}

The lineAggregator has to create an appropriate String including all the linebreaks, so that everyDetail is written on its own line in the file.

Of course, you don't have to use a FlatFileWriter and just open an file, use the lineAggregator to create to line and save the line to the file.



来源:https://stackoverflow.com/questions/38952058/new-output-file-for-each-item-passed-into-flatfileitemwriter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!