Spring Batch: Writing data to multiple files with dynamic File Name

后端 未结 2 1980
野性不改
野性不改 2020-12-16 05:16

I have a requirement to get the data from a database and write that data to files based on the filename given in the database.

This is how data is defined in the da

2条回答
  •  情话喂你
    2020-12-16 05:57

    I'm not sure but I don't think there is an easy way of obtaining this. You could try to build your own ItemWriter like this:

    public class DynamicItemWriter  implements ItemStream, ItemWriter {
    
        private Map> writers = new HashMap<>();
    
        private LineAggregator lineAggregator;
    
        private ExecutionContext executionContext;
    
        @Override
        public void open(ExecutionContext executionContext) throws ItemStreamException {
            this.executionContext = executionContext;
        }
    
        @Override
        public void update(ExecutionContext executionContext) throws ItemStreamException {
        }
    
        @Override
        public void close() throws ItemStreamException {
            for(FlatFileItemWriter f:writers.values()){
                f.close();
            }
        }
    
        @Override
        public void write(List items) throws Exception {
            for (YourEntry item : items) {
                FlatFileItemWriter ffiw = getFlatFileItemWriter(item);
                ffiw.write(Arrays.asList(item));
            }
        }
    
        public LineAggregator getLineAggregator() {
            return lineAggregator;
        }
    
        public void setLineAggregator(LineAggregator lineAggregator) {
            this.lineAggregator = lineAggregator;
        }
    
    
        public FlatFileItemWriter getFlatFileItemWriter(YourEntry item) {
            String key = item.FileName();
            FlatFileItemWriter rr = writers.get(key);
            if(rr == null){
                rr = new FlatFileItemWriter<>();
                rr.setLineAggregator(lineAggregator);
                try {
                    UrlResource resource = new UrlResource("file:"+key);
                    rr.setResource(resource);
                    rr.open(executionContext);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                writers.put(key, rr);
                //rr.afterPropertiesSet();
            }
            return rr;
        }
    }
    

    and configure it as a writer:

    
            
            
                
                
            
        
    

提交回复
热议问题