Solution for org.xml.sax.SAXParseException:
Premature end of file. at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:249) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284) at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)



Are you running into below exception when executing java code related to parsing/validating an xml?

org.xml.sax.SAXParseException: Premature end of file.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:249)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)

Please review your code carefully. The error message is misleading. Below is a sample code snippet that can cause this exception:

InputStream outStream = new ByteArrayInputStream(xml.getBytes());
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(namespaceAware);
docFactory.setValidating(false);
SchemaFactory schemaFactory = SchemaFactory
.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = schemaFactory
.newSchema(new Source[]{new StreamSource(xsd)});
Validator validator = schema.newValidator();
Source source = new StreamSource(outStream);
validator.validate(source);
logger.info("XML is valid");
DocumentBuilder builder = docFactory.newDocumentBuilder();
builder.setErrorHandler(new SimpleErrorHandler());
Document doc = builder.parse(outStream);

In above code we are validating and then trying to parse an xml. The issue is in the highlighted line. The same outStream is being used for both validating and parsing. This is not allowed.Standard processing of streams is to close them on as part of cleanup. So applications should not attempt to re-use such streams. In above code, to fix the issue you will have to create a new stream. Replace the bold line with below two lines and you will fix the problem:

InputStream outStream1 = new ByteArrayInputStream(xml.getBytes());
Document doc = builder.parse(outStream);