Spring批处理输入资源必须存在(阅读器处于“严格”模式)错误

ttt*_*ttt 8 java spring spring-batch

我使用 Spring Batch 来解析 csv 文件。当文件在资源目录中时效果很好,但在其他地方不起作用。我得到错误

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

我的代码

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;
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码效果很好

File file = new File(filePath);
Run Code Online (Sandbox Code Playgroud)

Els*_*yed 5

使用 PathResourceorg.springframework.core.io ,它为我工作

@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();
}
Run Code Online (Sandbox Code Playgroud)


ttt*_*ttt 4

刚刚找到解决方案使用org.springframework.core.io.UrlResource;类而不是org.springframework.core.io.ClassPathResource;