Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring batch Input resource must exist (reader is in 'strict' mode) error

I use Spring Batch for parse csv file. It works great, when file in resource directory, but doesn't work from another place. I get suck error

Caused by: java.lang.IllegalStateException: Input resource must exist (reader is in 'strict' mode): class path resource [c:/data/geodata1.csv]

My code

spring.datasource:
    driverClassName: org.h2.Driver
    url: jdbc:h2:mem:mydb;MODE=Oracle
server:
  port: 9001
geodata:
  file: c:/data/geodata1.csv

@Value("${geodata.file}")
private String filePath;

@Bean
public FlatFileItemReader<Person> reader() {
    FlatFileItemReader<Person> reader = new FlatFileItemReader<Person>();
    reader.setResource(new ClassPathResource(filePath));
    reader.setLineMapper(new DefaultLineMapper<Person>() {{
        setLineTokenizer(new DelimitedLineTokenizer() {{
            setNames(new String[] {"clientId", "longitude", "latitude", });
        }});
        setFieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {{
            setTargetType(Person.class);
        }});
    }});
    return reader;
}

But this code works good

File file = new File(filePath);
like image 846
ttt Avatar asked Sep 25 '17 10:09

ttt


Video Answer


1 Answers

use PathResource from org.springframework.core.io , it worked for me

@Bean
@StepScope
public FlatFileItemReader<CourseCountry> reader(@Value("#{jobParameters[fullPathFileName]}") String pathToFile) {
    return new FlatFileItemReaderBuilder<CourseCountry>()
      .name("studentItemReader")        
      .resource(new PathResource(pathToFile))
      .lineMapper(lineMapper())
      .linesToSkip(1)
      .build();
}
like image 66
Elsayed Avatar answered Sep 19 '22 13:09

Elsayed