Premature end of file Error

gencay picture gencay · Jun 9, 2011 · Viewed 18k times · Source

I am using XSL to configure my XML file into a smaller XML. My code fragments are so:

public class MessageTransformer {

public static void main(String[] args) {
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        Transformer transformer = transformerFactory.newTransformer (new StreamSource("sample.xsl"));
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(new StreamSource ("sample.xml"),  
            new StreamResult( new FileOutputStream("sample.xml"))
        );
    }
    catch (Exception e) {
        e.printStackTrace( );
    }    
}   
}

I got this error

ERROR:  'Premature end of file.'
ERROR:  'com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: Premature end of file.'

When I use XSL file to transform XML manually I don' t have any problem. However with this JAVA file I cannot transform.

What would be the problem?

Answer

wjans picture wjans · Jun 9, 2011

You are streaming from and to the same file. Try changing it to something like this:

transformer.transform(new StreamSource ("sample.xml"),  
        new StreamResult( new FileOutputStream("sample_result.xml"))
    );