Java JaxB Unmarshaller给出org.xml.sax.SAXParseException文件的过早结束

时间:2018-05-23 13:35:01

标签: java jaxb

private Course unmarshalCourse(InputStream is) throws CourseServiceException, IOException{
        Course c=null;
        try{
            JAXBContext jc = JAXBContext.newInstance( "com.sakai.domain" );
            Unmarshaller u = jc.createUnmarshaller();
            String theString = IOUtils.toString(is, "UTF-8"); 
            log.debug("---------xml"+theString);
            Object value = u.unmarshal(is);

            c=(Course)value;
            log.debug("---------course"+c);
        }catch(JAXBException e){
            //je.printStackTrace();
            throw new CourseServiceException(e, Error.CONFIG);
        }
        return c;
    }

我将输入流作为xml。当我尝试解除错误后触发它。请帮助。

  

[org.xml.sax.SAXParseException; lineNumber:1; columnNumber:1;   文件过早结束。] com.course.logic.CourseServiceException:   javax.xml.bind.UnmarshalException     - 链接异常:[org.xml.sax.SAXParseException; lineNumber:1; columnNumber:1;文件过早结束。]

1 个答案:

答案 0 :(得分:2)

问题是由您使用InputStream is的方式引起的。

String theString = IOUtils.toString(is, "UTF-8"); 
log.debug("---------xml"+theString);
Object value = u.unmarshal(is);

首先,通过读取它来消耗所有的InputStream IOUtils.toString(is, "UTF-8")。当然,在那之后你就到了 流的结束。然后,您尝试继续从此流中读取 按u.unmarshal(is)。毫不奇怪,你得到一个例外 Premature end of file现在。

要解决此问题,请勿从InputStream is解组。 但是从String theString解释:

String theString = IOUtils.toString(is, "UTF-8"); 
log.debug("---------xml"+theString);
Object value = u.unmarshal(new StringReader(theString));