Java, StaX simple code but get parse error, premature end of file

Ben picture Ben · Mar 25, 2012 · Viewed 8.7k times · Source

I'm trying to figure out IO using StaX, but I keep getting "malformed" and "premature EOF" errors from the reader. This is reading code created using StaX, as in the following example.

I've boiled down my code to the simplest configuration, and still get an error. Where is this coming from?

SSCCE (should throw error)

package XMLTest;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;

public class SaveLoadTest {
    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        final String FILE = "test.xml";

        //////////// WRITE
        final XMLOutputFactory OFACT = XMLOutputFactory.newInstance();
        final XMLEventFactory EFACT = XMLEventFactory.newInstance();
        final XMLEventWriter WRITER = OFACT.createXMLEventWriter(new FileOutputStream(FILE));

        WRITER.add(EFACT.createStartDocument());
        WRITER.add(EFACT.createComment("As basic as it gets."));
        WRITER.add(EFACT.createEndDocument());
        WRITER.close();

        //////////// READ
        final XMLInputFactory IFACT = XMLInputFactory.newInstance();
        final XMLEventReader READER = IFACT.createXMLEventReader(new FileInputStream(FILE));

        while (READER.hasNext()) {
            READER.nextEvent();
        }
    }
}

And the error:

Exception in thread "main" javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,49]
Message: Premature end of file.
    at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:594)
    at com.sun.xml.internal.stream.XMLEventReaderImpl.nextEvent(XMLEventReaderImpl.java:85)
    at XMLTest.SaveLoadTest.main(SaveLoadTest.java:34)

I've had a look at several other SO questions (this or this seem most relevant) but I'm having trouble relating them to this situation...

EDIT

Also, I have tried this reading and writing in separate operations, and the same thing happens.

EDIT THE SECOND

XML output file, as requested.

<?xml version="1.0"?><!--As basic as it gets.-->

Answer

jimr picture jimr · Mar 25, 2012

It's expecting the XML file to have a root element.

If your output code is changed to create an element it works:

    WRITER.add(EFACT.createStartDocument());
    WRITER.add(EFACT.createStartElement("", "", "element"));
    WRITER.add(EFACT.createEndElement("", "", "element"));
    WRITER.add(EFACT.createEndDocument());

Outputs into the file

    <?xml version="1.0" encoding="UTF-8"?><element></element>

And then reads the first event with no errors.