gpt4 book ai didi

java - spring-batch 读取 null int 值

转载 作者:行者123 更新时间:2023-12-02 11:19:46 26 4
gpt4 key购买 nike

我有一个文件阅读器来读取客户 csv 文件如果 int 字段为空我收到错误 字段“custPaymentTerm”上对象“目标”中的字段错误:拒绝值 [];代码 [typeMismatch.target.custPaymentTerm,typeMismatch.custPaymentTerm,typeMismatch.int,typeMismatch];参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [target.custPaymentTerm,custPaymentTerm];参数[];默认消息[custPaymentTerm]];默认消息 [无法将类型“java.lang.String”的属性值转换为属性“custPaymentTerm”所需的类型“int”;嵌套异常是 java.lang.NumberFormatException: For input string: ""]

读取文件的类。spring-batch-job 如何读取、处理 null int 值。

我的 csv 数据文件的第二行抛出空错误!

public static void readCustomers(String pathToFile) throws Exception {  
System.out.println(" THE path is:"+pathToFile);
FlatFileItemReader<Customer> reader = new FlatFileItemReader<>();
reader.setResource(new FileSystemResource(pathToFile));


DelimitedLineTokenizer delimitedTokeniser = new DelimitedLineTokenizer();
delimitedTokeniser.setNames(new String[]{"valueA", "custPaymentTerm","valueC"});
DefaultLineMapper<Customer> lineMapper = new DefaultLineMapper<Customer>();
lineMapper.setLineTokenizer(delimitedTokeniser);
lineMapper.setFieldSetMapper(new BeanWrapperFieldSetMapper<Customer>() {{setTargetType(Customer.class);}});
reader.setLineMapper(lineMapper);
reader.setLinesToSkip(1); //do not read the first line of the csv file.
reader.open(new ExecutionContext());
Customer store = null;
List<Customer> stores = new ArrayList<>();
do {
store = reader.read();
if (store != null) {
System.out.println("######## ------->"+store.getCustPaymentTerm());
stores.add(store);
}
} while (store != null);
}

public Customer(){
String valueA;
int custPaymentTerm;
String valueC;
}

数据文件内容

apple,1,cat
dog,,rat

最佳答案

您应该编写自己的 FieldSetMapper 实现并将其添加到您的线路映射器中,而不是使用 Spring 提供的 BeanWrapperFieldSetMapper。

 lineMapper.setFieldSetMapper(new MyCustomFieldSetMapper());

在该类的 mapFieldSet(...) 方法中,您可以创建一个包含所有映射字段的新客户。这可能看起来像这样:

Customer mapFieldSet(FieldSet fs) {
Customer customer = new Customer();
customer.setCustPaymentTerm(fs.readInt("custPaymentTerm", 0);
// set your other fields here
return customer;
}

“readInt(..., 0)”调用中的零是从行读取空白值时的默认值。

关于java - spring-batch 读取 null int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50020445/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com