文件过早结束错误

gen*_*cay 4 java xslt transformer-model

我正在使用XSL将我的XML文件配置为更小的XML.我的代码片段是这样的:

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( );
    }    
}   
}
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误

ERROR:  'Premature end of file.'
ERROR:  'com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: Premature end of file.'
Run Code Online (Sandbox Code Playgroud)

当我使用XSL文件手动转换XML时,我没有任何问题.但是使用这个JAVA文件我无法转换.

会出现什么问题?

wja*_*ans 6

您正在从同一个文件流式传输.尝试将其更改为以下内容:

transformer.transform(new StreamSource ("sample.xml"),  
        new StreamResult( new FileOutputStream("sample_result.xml"))
    );
Run Code Online (Sandbox Code Playgroud)

  • @gencay - 你能告诉我们你是如何解决的吗? (9认同)