How to skip lines with ItemReader in Spring-Batch?

后端 未结 5 818
陌清茗
陌清茗 2021-01-16 15:39

I have a custom item reader that transforms lines from a textfile to my entity:

public class EntityItemReader extends AbstractItemStreamItemReader

        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-16 16:27

    For skipping lines you can throw Exception when you want to skip some lines, like below.

    My Spring batch Step

    @Bean
    Step processStep() {
    
        return stepBuilderFactory.get("job step")
                    .chunk(1000)
                    .reader(ItemReader)
                    .writer(DataWriter)
                    .faultTolerant() //allowing spring batch to skip line 
                    .skipLimit(1000) //skip line limit
                    .skip(CustomException.class) //skip lines when this exception is thrown
                    .build();
    }
    

    My Item reader

    @Bean(name = "reader")
    public FlatFileItemReader fileItemReader() throws Exception {
    
        FlatFileItemReader reader = new FlatFileItemReader();
    
        reader.setResource(resourceLoader.getResource("c://file_location/file.txt"));
        CustomLineMapper lineMapper = new CustomLineMapper();
        reader.setLineMapper(lineMapper);
    
        return reader;
    
        }
    

    My custom line mapper

    public class CustomLineMapper implements LineMapper {
    
    @Override
    public String mapLine(String s, int i) throws Exception {
    
        if(Condition) //put your condition here when you want to skip lines
            throw new CustomException();
        return s;
    }
    }
    

提交回复
热议问题