Search code examples
javasocketsstreamsaxjaxp

Best way to close a stream an SAX parser is reading during the parsing process?


Let's get straight to my question: I have a socket and all input coming via this socket / stream is parsed by my SAX parser. Now, upon a certain parsing event I'd like to close the socket / stream from within my SAX event handler. Also, I want to close the stream from outside in a certain case while the parser is still working. Unfortunately, I can't do the one thing or the other without having an exception thrown by the parser (unexpected document ending...). Ok, I could catch this exception, but do you know a solution how to securely close the stream?


Solution

  • I don't think you can easily do this. You're giving the SAX parser a resource (a stream) to read from, and then you're closing it and the SAX parser still expects to read from it - hence it's (not unreasonably!) throwing an 'unexpected document ending'.

    If you want to do this cleanly, I think your SAX parser handler that you've implemented should silently swallow events once you've decided to ignore further events.

    e.g. your implementations of startElement(), endElement() etc. should perform a check to see whether you're still interested in these events before processing.

    That way the SAX parser can run cleanly to the end of the document without you processing any more events.

    Alternatively, why not record the fact that you've closed the input stream, and then when you get an 'unexpected document ending' event, see if it in fact was expected. And only log an error if it really was unexpected.