How to move files to archive and error folders after processing

别来无恙 提交于 2021-01-01 06:59:35

问题


Job runs once and try to process all the files available in a source folder in a step. Further it need to do removal of processed/tried but failed files from the source folder to another subsequent folders (/_archived, /_faild). What is the best way to move successfully processed files in archive folder and unsuccessfull files in error folder categorically using spring batch.


回答1:


you can add separate tasklet or use JobExecutionListener.afterJob hook to move files.

Below is sample example for moving files using tasklet

Java config

@autowired
private MoveFilesTasklet moveFilesTasklet


    @Bean
    protected Step moveFiles() {
        return steps
          .get("moveFiles")
          .tasklet(moveFilesTasklet)
          .build();
    }

    @Bean
    public Job job() {
        return jobs
          .get("taskletsJob")
          .start(processFiles())
          .next(moveFiles())          
          .build();

Tasklet

@Component
public class MoveFilesTasklet implements Tasklet {     
        private String filePath ="someFilePAth";

    @Override
    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {    

        final File directory = new File(filePath);
        Arrays.asList(directory.listFiles((dir, name) -> name.matches("yourfilePrefix".*?")))
                .stream()
                .forEach(singleFile -> singleFile.renameTo(new File("someNewFilePath")));               
        return RepeatStatus.FINISHED;

    }

}


来源:https://stackoverflow.com/questions/52941094/how-to-move-files-to-archive-and-error-folders-after-processing

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