Search code examples
javabean-io

Continue parsing of records if exception occurs on some record in BeanIO


I am using BeanIO to convert flat file into list of Object. Using following code snippet.

while ((MyCustomRecord obj = (MyCustomRecord) in.read()) != null) {
         System.out.println(obj);
}

But problem with this is, if exception occurs during parsing of some record, It immediately stops processing records. I want to suppress such exception and want it to continue processing of next records.

Is there a way to do this?

One thing that I can try is to put in.read in body of while block and wrap it around try/catch but then how would I detect end condition. There seems to be no method that tells end of records.

Thanks Jitendra


Solution

  • Found answer in BeanIO reference documentation. I missed that earlier.

    It can be done by registering your custom ErrorHandler in BeanReader.

    in.setErrorHandler(new BeanReaderErrorHandlerSupport() {
                public void invalidRecord(InvalidRecordException ex) throws Exception {
                    System.out.println(ex.getLocalizedMessage());
                } 
    });
    

    http://beanio.org/docs/reference/index.html#StreamValidation