Spring Batch DelimitedLineTokenizer - 用双引号解析字符串 [英] Spring Batch DelimitedLineTokenizer - parse String with Double Quotes
问题描述
我有带双引号的记录,这导致 FlatFileParseException.记录是这样的ABC|XYZ|0|1|INVALID "STRING WITH DOUBLE QUOTES USED|E
.
I have records with double quotes which is giving FlatFileParseException. Records are like this ABC|XYZ|0|1|INVALID "STRING WITH DOUBLE QUOTES USED|E
.
@Bean
public LineMapper < Product > lineMapper() {
DefaultLineMapper < Product > lineMapper = new DefaultLineMapper < > ();
DelimitedLineTokenizer lineTokeniser = new DelimitedLineTokenizer("|");
lineTokeniser.setNames("Type", "Owner", "Name",
"Id", "Discreption", "Category");
lineTokeniser.setIncludedFields(0, 1, 2, 3, 4, 5);
BeanWrapperFieldSetMapper < Product > fieldSetMapper = new BeanWrapperFieldSetMapper < > ();
fieldSetMapper.setTargetType(Product.class);
lineMapper.setLineTokenizer(lineTokeniser);
lineMapper.setFieldSetMapper(fieldSetMapper);
return lineMapper;
}
@Bean
public FlatFileItemReader < Product > reader() {
FlatFileItemReader < Product > itemReader = new FlatFileItemReader < > ();
itemReader.setLineMapper(lineMapper());
itemReader.setResource(new FileSystemResource("c:/files/Product.txt"));
return itemReader;
}
我正在使用 DelimitedLineTokenizer 并按|"进行拆分.DelimitedLineTokenizer lineTokeniser = new DelimitedLineTokenizer("|");
I am using DelimitedLineTokenizer and splitting by "|".
DelimitedLineTokenizer lineTokeniser = new DelimitedLineTokenizer("|");
有关如何处理此问题的任何建议.
Any suggestions on how can I handle this.
推荐答案
您需要扩展 DelimitedLineTokenizer 并从 isQuoteCharacter 返回 false 以解决此问题.
You need to extend DelimitedLineTokenizer and return false from isQuoteCharacter to fix this.
查看此工作代码:
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.file.transform.FieldSet;
public class PlainTests {
public static void main(String[] args) {
DelimitedLineTokenizer t = new MyDelimitedLineTokenizer("|");
t.setNames("Type", "Owner", "Name", "Id", "Description", "Category");
FieldSet fs = t.tokenize("ABC|XYZ|0|1|INVALID \"STRING WITH DOUBLE QUOTES USED|E");
System.out.println(String.join("\n", fs.getValues()));
//strip the double quote from Description if needed
}
}
class MyDelimitedLineTokenizer extends DelimitedLineTokenizer {
public MyDelimitedLineTokenizer(String d) {
super(d);
}
@Override
protected boolean isQuoteCharacter(char c) {
return false;
}
}
另见:Spring Batch - FlatFileParseException(用双引号记录)
这篇关于Spring Batch DelimitedLineTokenizer - 用双引号解析字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!