Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

spring - Manage I/O and POI exception in a customReaderItem

I'm using a customReader that implements ItemReader. My reader take information from xls and treat it row by row. My constructor take Iterator value that will be read on each read() iteration. I'm trying to find a suitable way to manage exception. I look through SkipListener and ReaderListener onReadError. But Ican't use either because my exception will be thrown in the constructor before attempting read() method.

Is there any way to do that in order to allow me to manage properly action1/2/3 respectively to exceptions ?

@Component
public class CustomReaderFile implements ItemReader<Row> {

    private final Iterator<Row> data;
    private static final String FILE_NAME = "";

    public CustomReaderFile() throws Exception {
        this.data = iteratorFromXls();
    }

    @Override
    public Row read() throws Exception {
        if (this.data.hasNext()) {
            return this.data.next();
        } else {
            return null;
        }
    }


    public static Iterator<Row> iteratorFromXls() throws Exception {
        Iterator<Row> iterator = null;
        try {
            FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
            Workbook workbook = new XSSFWorkbook(excelFile);
            Sheet dataTypeSheet = workbook.getSheetAt(0);
            iterator = dataTypeSheet.iterator();  
        } catch (FileNotFoundException e) {
        //action1
        } catch (IOException e) {
        //action2
        } catch (NotOfficeXmlFileException e){
        //action3
        }

        return iterator;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is actually the reader's initialization code. The reading part is nothing more than calling .next on the iterator.

So I would make the reader implement ItemStreamReader and put the initialization code in the open method, in which you can throw an exception to signal to Spring Batch that the reader's initialization has failed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...