弹簧批输入资源必须存在(读取器处于'strict'模式)错误



我将Spring Batch用于Parse CSV文件。当资源目录中的文件时,它效果很好,但在其他地方不起作用。我得到吸吮错误

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

我的代码

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;
}

但是此代码效果很好

File file = new File(filePath);

使用 pathResource 来自 org.springframework.core.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();
}

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

我遇到了同样的问题,我会使用org.springframework.core.io.io.filesystemsource类,例如:文件:c: data geodata1.csvreader.setResource(新的filesystemresource(file));

@Bean
public FlatFileItemReader<Person> reader() {
   new FlatFileItemReaderBuilder<Person>()
                .name("JobName")
                .resource(new PathResource(getReceivedFilePath("Location")))
                .targetType("Targetclass".class)
                .linesToSkip(" count of no of lines to skip")
                .delimited()
                .delimiter(recordSeparator)
                .includedFields(new Integer[] { 0, 1})
                .names(new String[] { "param1 in target class","param2 in target class etc" })
                .build();
}

u传递到pathResource的getReceivedfilepath应该如下,它以等于或结束的任何文件等。

 public String getReceivedFilePath(String fileName) {
        File directory = new File(file.location);
        if (directory.isDirectory()) {
            File[] files = directory.listFiles((dir, name) -> name.toLowerCase().endsWith("extension.type"));
            for (File file : files) {
                if (FilenameUtils.getBaseName(file.getName()).startsWith(FilenameUtils.getBaseName(fileName))) {
                    return file.getAbsolutePath();
                }
            }
        }
        return directory.getName();
    }

解决方案2:您可以使用PathResource,但是您的文件名应匹配您提供的确切路径

ex:new PathResource(c: files filename.csv&quot; qus;)

相关内容

最新更新