如何使用Spring Batch读取具有不同列数的CSV文件 [英] How to read CSV file with different number of columns with Spring Batch
问题描述
我有一个没有固定列数的CSV文件,例如:
I have a CSV file that doesn't have a fixed number of columns, like this:
col1,col2,col3,col4,col5
val1,val2,val3,val4,val5
column1,column2,column3
value1,value2,value3
是否可以使用Spring Batch读取此类CSV文件?
Is there any way to read this kind of CSV file with Spring Batch?
我试图这样做:
<bean id="ItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<!-- Read a csv file -->
<property name="resource" value="classpath:file.csv" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<!-- split it -->
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names"
value="col1,col2,col3,col4,col5,column1,column2,column3" />
</bean>
</property>
<property name="fieldSetMapper">
<bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="myBean" />
</bean>
</property>
</bean>
</property>
</bean>
但是结果是这个错误:
推荐答案
您可以根据模式使用PatternMatchingCompositeLineMapper
每行委派给相应的LineMapper
实现.从那里,您的每个代表将使用DelimtedLineTokenizer
和FieldSetMapper
来相应地映射线.
You can use the PatternMatchingCompositeLineMapper
to delegate to the appropriate LineMapper
implementation per line based on a pattern. From there, each of your delegates would use a DelimtedLineTokenizer
and a FieldSetMapper
to map the line accordingly.
您可以在以下文档中详细了解此内容: http://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/item/file/mapping/PatternMatchingCompositeLineMapper.html
You can read more about this in the documentation here: http://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/item/file/mapping/PatternMatchingCompositeLineMapper.html
这篇关于如何使用Spring Batch读取具有不同列数的CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!