简体   繁体   中英

Java JaxB Unmarshaller giving org.xml.sax.SAXParseException Premature end of file

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

Im getting input stream as a xml.when i try to unmarshal it following error is triggered.please help.

[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.] com.course.logic.CourseServiceException: javax.xml.bind.UnmarshalException - with linked exception: [org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.]

The problem is caused by the way you use the InputStream is .

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

First you consume all of the InputStream by reading it with IOUtils.toString(is, "UTF-8") . Of course, after that you are at end of stream. Then you try to continue reading from this stream by u.unmarshal(is) . No surprise, you get an exception with Premature end of file now.

To fix this, do not unmarshal from InputStream is . but unmarshal from String theString :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM