我想将spring-batch
配置为按顺序读取特定文件夹中的所有csv
个文件。
以下操作不起作用,因为委托将尝试打开名为*.csv
的文件,这当然是无效的。我在这里需要改变什么?
@Bean
public ItemReader<String> reader() {
MultiResourceItemReader<String> reader = new MultiResourceItemReader<>();
reader.setResources(new Resource[] {new FileSystemResource("/myfolder/*.csv")});
reader.setDelegate(new FlatFileItemReader<>(..));
return reader;
}
等效的xml配置如下所示,我怎样才能将它重写为仅限java的配置?
<bean id="reader" class="org.springframework.batch.item.file.MultiResourceItemReader">
<property name="resources" value="/mypfolder/*.csv"/>
<property name="delegate" ref="flatFileItemReader"/>
</bean>
答案 0 :(得分:9)
我认为你应该使用PathMatchingResourcePatternResolver
。
答案 1 :(得分:8)
像这样使用PathMatchingResourcePatternResolver。
@Bean
public ItemReader<String> reader() {
Resource[] resources = null;
ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
try {
resources = patternResolver.getResources("/myfolder/*.csv");
} catch (IOException e) {
e.printStackTrace();
}
MultiResourceItemReader<String> reader = new MultiResourceItemReader<>();
reader.setResources(resources);
reader.setDelegate(new FlatFileItemReader<>(..));
return reader;
}
答案 2 :(得分:2)
从绝对文件路径:
中读取多个文件 @Bean
public MultiResourceItemReader<POJO> multiResourceItemReader() {
MultiResourceItemReader<POJO> resourceItemReader = new MultiResourceItemReader<POJO>();
ClassLoader cl = this.getClass().getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
Resource[] resources = resolver.getResources("file:" + filePath );
resourceItemReader.setResources(resources);
resourceItemReader.setDelegate(reader());
return resourceItemReader;
}
@Bean
public FlatFileItemReader<POJO> reader() {
FlatFileItemReader<POJO> reader = new FlatFileItemReader<POJO>();
reader.setLineMapper(new DefaultLineMapper() {{
setLineTokenizer(new DelimitedLineTokenizer() {{
setNames(new String[]{"id1", "POJO"});
}});
setFieldSetMapper(new BeanWrapperFieldSetMapper<POJO>() {{
setTargetType(POJO.class);
}});
}});
return reader;
}
答案 3 :(得分:1)
或者,@ Value批注可用于让ResourceArrayPropertyEditor将字符串转换为Resource []。
@Bean
@StepScope
public ItemReader<String> reader(
@Value("file:/myfolder/*.csv") Resource[] resources
) {
MultiResourceItemReader<String> reader = new MultiResourceItemReader<>();
reader.setResources(resources);
reader.setDelegate(new FlatFileItemReader<>(..));
return reader;
}