Spring Batch - Validate Header Lines in input csv file and skip the file if it invalidates

后端 未结 1 1732
北海茫月
北海茫月 2021-01-06 17:49

I have a simple job as below:


 
  

        
相关标签:
1条回答
  • 2021-01-06 18:04

    Looking code of FlatFileItemReader file stop condition is managed;

    1. with private field boolean noInput
    2. with private function readLine() used in protected doRead()

    IMHO the best solution is to throw a runtime exception from your skippedLineCallback and manage error as reader exhaustion condition.

    Foe example writing your delegate in this way

    class SkippableItemReader<T> implements ItemStreamReader<T> {
      private ItemStreamReader<T> flatFileItemReader;
      private boolean headerError = false;
    
      void open(ExecutionContext executionContext) throws ItemStreamException {
        try {
          flatFileItemReader.open(executionContext);
        } catch(MyCustomExceptionHeaderErrorException e) {
          headerError = true;
        }
      }
    
      public T read() {
        if(headerError)
          return null;
        return flatFileItemReader.read();
      }
    
      // Other functions delegation
    }
    

    (you have to register delegate as stream manually,of course)
    or extending FlatFileItemReader as

    class SkippableItemReader<T> extends FlatFileItemReader<T> {
      private boolean headerError = false;
    
      protected void doOpen() throws Exception {
        try {
          super.doOpen();
        } catch(MyCustomExceptionHeaderErrorException e) {
          headerError = true;
        }
      }
    
      protected T doRead() throws Exception {
        if(headerError)
          return null;
        return super.doRead();
      }    
    }
    

    The code has been written directly without test so there can be errors, but I hope you can understand my point.
    Hope can solve your problem

    0 讨论(0)
提交回复
热议问题