spring flatfile:block read null last line

时间:2018-05-01 01:19:02

标签: java spring spring-boot spring-batch

我有方法,它接收上传的csv平面文件,处理它并打印所有值。

问题是,它仍然尝试在上次读取并处理该值并抛出nullpointerexception错误。我该怎么做。 ?

在循环结束时,我添加了while (newPs != null),所以它不应再处理循环了。

public void readPsFile(MultipartFile batchFile) throws Exception {  
    FlatFileItemReader<ProductService> reader = new FlatFileItemReader<>();
    DelimitedLineTokenizer delimitedTokeniser = new DelimitedLineTokenizer();
    delimitedTokeniser.setNames(new String[]{ "name"});
    DefaultLineMapper<ProductService> lineMapper = new DefaultLineMapper<ProductService>();
    lineMapper.setLineTokenizer(delimitedTokeniser);
    lineMapper.setFieldSetMapper(new BeanWrapperFieldSetMapper<ProductService>() {{setTargetType(ProductService.class);}});
    ByteArrayResource y= new ByteArrayResource(batchFile.getBytes());
    reader.setResource(y);
    reader.setLineMapper(lineMapper);
    reader.setLinesToSkip(1); //do not read the first line of the csv file.
    reader.open(new ExecutionContext());

    reader.open(new ExecutionContext());
    ProductService newPs = null;
    do {
        try {
        newPs = reader.read();
        System.out.println("--->"+newPs.getName());
    }catch(Exception e) {
        e.printStackTrace();
    } while (newPs != null);
}

1 个答案:

答案 0 :(得分:0)

因为您在调用getName()时已经尝试取消引用null之后,为时太晚了。请勿使用do/while

while ((newPs = reader.read()) != null) {
    System.out.println("--->"+newPs.getName())
}