TransformerException:文件错误提前结束

时间:2017-10-27 09:49:25

标签: java xslt xml-parsing jaxb java-stream

我正在尝试基于编组的xml和xslt以及一些问题生成outFile。

一段代码从object生成xml流。

 JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeFormat.class);
 ByteArrayOutputStream os = new ByteArrayOutputStream();
 Marshaller marshaller = jaxbContext.createMarshaller();
 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);         
 marshaller.marshal(employeeFormat,os);
 outEmpFile(new ByteArrayInputStream(os.toByteArray())); 

此方法生成outFile,将xml作为输入

public void outEmpFile(ByteArrayInputStream inputStream) throws IOException {
    File template = new File("C/workspace/files/Employee.xslt"); 
    File outFile = new File(C:/workspace/files/Employee.java");

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer(new StreamSource(template));             
    transformer.transform(new StreamSource(inputStream),new StreamResult(outFile));
}

运行代码时出现TransformerException:

 ERROR:  'Premature end of file.'javax.xml.transform.TransformerException: javax.xml.transform.TransformerException: 

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

输入xml和xslt都会在在线工具中生成预期输出 - http://www.utilities-online.info/xsltransformation

此代码在控制台中提供正确的xml文件。

public void  byteToString(ByteArrayInputStream is) {       
    int size = is.available();
    char[] theChars = new char[size];
    byte[] bytes    = new byte[size];

 is.read(bytes, 0, size);
    for (int i = 0; i < size;)
        theChars[i] = (char)(bytes[i++]&0xff);

    System.out.println("Xml String :"+ new String(theChars));
  }

有关此问题的任何帮助吗?

1 个答案:

答案 0 :(得分:0)

问题是在传入transform方法之前消耗了输入流,导致文件过早结束错误。 有关详情,请参阅此处 - org.xml.sax.SAXParseException: Premature end of file for *VALID* XML