Reputation: 253
I'm developing a batch application using Spring Batch with Java 11. This is my reader() method:
@SuppressWarnings("unchecked")
@Bean
public FlatFileItemReader<MyClass> reader() {
BeanWrapperFieldSetMapper beanWrapperMapper = new BeanWrapperFieldSetMapper<MyClass>();
beanWrapperMapper.setTargetType(MyClass.class);
return new FlatFileItemReaderBuilder<MyClass>()
.name("MyClassReader")
.resource(new FileSystemResource(inputFolder.concat(File.separator).concat("my-input-file.csv")))
.delimited()
.names("field1", "field2")
.fieldSetMapper(beanWrapperMapper)
.build();
}
I did several tests and when the file my-input-file.csv
is there, the batch works fine. However, I would like to get the following behavior: if the file my-input-file.csv
is missing, I still want something written to the output file and no errors be raised.
Right now, if I run the batch but the file is not in the folder, this error comes up:
IllegalStateException: Input resource must exist (reader is in 'strict' mode): path [C:\\Users\\username\\Desktop\\src\\test\\resources\\my-input-file.csv]
I am aware that the error is because the file could not be found. But I really would like to handle this case to generate a different output file (and I don't want the batch process to fail).
How can this be done?
Upvotes: 0
Views: 662
Reputation: 104
set the strict property to false so that input resource exceptions would not happen.
check the readCount after the batch job is completed. if readCount == 0, means no data, and you handle your logic here.
example for your case (implementing the JobExecutionListener):
@Override
public void afterJob(JobExecution jobExecution) {
StepExecution[] stepExecutions = jobExecution.getStepExecutions().toArray(new StepExecution[]{});
StepExecution stepExecution = stepExecutions[0];
long readCount = stepExecution.getReadCount();
if (readCount == 0) {
// your logic
}
}
Upvotes: 1