我有一个文件读取器来读取客户的csv文件
如果int字段为空
我收到错误Field error in object 'target' on field 'custPaymentTerm': rejected value []; codes [typeMismatch.target.custPaymentTerm,typeMismatch.custPaymentTerm,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.custPaymentTerm,custPaymentTerm]; arguments []; default message [custPaymentTerm]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'custPaymentTerm'; nested exception is java.lang.NumberFormatException: For input string: ""]

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

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

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

最佳答案

代替使用Spring提供的BeanWrapperFieldSetMapper,您应该编写自己的FieldSetMapper实现并将其添加到linemapper中。

 lineMapper.setFieldSetMapper(new MyCustomFieldSetMapper());


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

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


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

07-27 14:07