[java] org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

I am getting very strange "Premature end of file." exception for last few days on one of our servers. The same configuration XML works fine on another server. We are using Tomcat 5.0.28 on both these servers. This code has been working for ages (7+ years), only after recent server crash, we faced this problem on one of the servers. There is no change in XML as well as Java parsing code. :(

The only difference I can see is in Java versions -

Problem Server java version "1.6.0_16" Java(TM) SE Runtime Environment (build 1.6.0_16-b01) Java HotSpot(TM) 64-Bit Server VM (build 14.2-b01, mixed mode)

Working Server java version "1.6.0_07" Java(TM) SE Runtime Environment (build 1.6.0_07-b06) Java HotSpot(TM) 64-Bit Server VM (build 10.0-b23, mixed mode)

Here is the Java code that has been working for several years -

private void readSource(final InputSource in ) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(in);
        Element elt = doc.getDocumentElement();

        this.readElement( elt );
    } catch ( Exception ex ) {
        ex.printStackTrace();
        throw new ConfigurationException( "Unable to parse configuration information", ex );
    }
}

And here is the exception.

[Fatal Error] :-1:-1: Premature end of file.
org.xml.sax.SAXParseException: Premature end of file.
        at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
        at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
        at com.circus.core.Configuration.readSource(Configuration.java:706)

I have already tried validating XML and found no errors there. Any idea where else can I look for possible problem?

Any pointers would be highly appreciated!

TIA, - Manish

This question is related to java xml xml-parsing

The answer is


It is a problem with Java InputStream. When the stream is read once the file offset position counter is moved to the end of file. On the subsequent read by using the same stream you'll get this error. So you have to close and reopen the stream again or call inputStream.reset() to reset the offset counter to its initial position.


This exception only happens if you are parsing an empty String/empty byte array.

below is a snippet on how to reproduce it:

String xml = ""; // <-- deliberately an empty string.
ByteArrayInputStream xmlStream = new java.io.ByteArrayInputStream(xml.getBytes());
Unmarshaller u = JAXBContext.newInstance(...)
u.setSchema(...);
u.unmarshal( xmlStream ); // <-- here it will fail

In our case it was an empty AndroidManifest.xml.

While upgrading Eclispe we ran into the usual trouble, and AndroidManifest.xml must have been checked into SVN by the build script after being clobbered.

Found it by compiling from inside Eclipse, instead of from the command line.


Please make sure that you are not consuming your inputstream anywhere before parsing. Sample code is following: the respose below is httpresponse(i.e. response) and main content is contain inside StringEntity (i.e. getEntity())in form of inputStream(i.e. getContent()).

InputStream rescontent = response.getEntity().getContent();
tsResponse=(TsResponse) transformer.convertFromXMLToObject(rescontent );

Are you sure that the XML file is in the correct character encoding? FileReader always uses the platform default encoding, so if the "working" server had a default encoding of (say) ISO-8859-1 and the "problem" server uses UTF-8 you would see this error if the XML contains any non-ASCII characters.

Does it work if you create the InputSource from a FileInputStream instead of a FileReader?


If input stream is not closed properly then this exception may happen. make sure : If inputstream used is not used "Before" in some way then where you are intended to read. i.e if read 2nd time from same input stream in single operation then 2nd call will get this exception. Also make sure to close input stream in finally block or something like that.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to xml-parsing

How to create XML file with specific structure in Java jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.' SyntaxError of Non-ASCII character xml.LoadData - Data at the root level is invalid. Line 1, position 1 XML Error: Extra content at the end of the document How to use sed to extract substring How to fix Invalid byte 1 of 1-byte UTF-8 sequence The best node module for XML parsing Parsing XML with namespace in Python via 'ElementTree' oracle plsql: how to parse XML and insert into table