【问题标题】:TransformerException: Premature end of file errorTransformerException:文件过早结束错误
【发布时间】:2018-04-08 21:23:43
【问题描述】:

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

一段代码从对象生成 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())); 

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

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));
  }

请帮忙解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    问题是输入流在传入转换方法之前被消耗,导致文件过早结束错误。 请参阅此了解更多信息 - org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

    【讨论】:

      猜你喜欢
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 2011-08-19
      相关资源
      最近更新 更多