How to interrupt POI streaming reader after reading the first line?

泪湿孤枕 提交于 2019-12-12 03:59:33

问题


I need to find a way to interrupt the stream reader (reading XML and parsing it with SAX) after first line. Meaning after I read the column names.

Any idea how to do that?

CODE:

    XSSFSheetXMLHandler.SheetContentsHandler mySheetContentsHandler = new MySheetContentsHandler(true, xlsxHeaders);
    File myFile = new File(filePath);
    OPCPackage pkg = OPCPackage.open(myFile.getPath());
    XSSFReader reader = new XSSFReader(pkg);
    StylesTable styles = reader.getStylesTable();
    ReadOnlySharedStringsTable sharedStrings = new ReadOnlySharedStringsTable(pkg);
    ContentHandler handler = new XSSFSheetXMLHandler(styles, sharedStrings, mySheetContentsHandler, true);

    XMLReader parser = XMLReaderFactory.createXMLReader();
    parser.setContentHandler(handler);
    parser.parse(new InputSource(reader.getSheetsData().next())); 

As you may see here, XSSFSheetXMLHandler.SheetContentsHandler is an interface with 4 methods. But how may I interrupt the reading of the file?

I have tried to do handler.endDocument(); which has executed in the implemented method of the interface endRow();, it didn't help, program went to another row without any interruption.


回答1:


A vague idea:

How about extend XSSFSheetXMLHandler, have a method "iterrupt" that sets some flag to true. And override start/endElement, start/endDocument. All you can do is something like below e.g

@Override
public void startElement(java.lang.String uri, java.lang.String localName, java.lang.String name, org.xml.sax.Attributes attributes) 
{
 if(interrupted)
 {
   //throw your custom exception;
 }
 super.startElement(uri,localName,name,attributes);

}

or in your class MySheetContentsHandler you can introduce the method, and then in cell(...) or endRow you can check the interrupt state before processing? Similarly you can override other methods. Worth a try?



来源:https://stackoverflow.com/questions/31939669/how-to-interrupt-poi-streaming-reader-after-reading-the-first-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!