org.xml.sax.SAXParseException: Premature end of file

当使用XML的schema去验证XML文档的时候曝出如题的错误,验证代码如下:

public static boolean validateXml(String xsd, InputStream input){
    boolean flag = true;
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema;
    try {
        Resource resource = new ClassPathResource(xsd);
        schema = factory.newSchema(resource.getURL());
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(input));
    } catch (SAXException | IOException e) {
        flag = false;
        logger.error("validate xml failed");
        e.printStackTrace();
    }
    return flag;
}

验证的代码如下:

InputStream input = new ClassPathResource("person.xml").getInputStream();
String xml = IOUtils.toString(input);
boolean flag = XmlUtils.validateXml("mapping.xsd", input);
System.out.println(flag);

当通过该方法去验证时报出org.xml.sax.SAXParseException:Premature end of file错误,经过调试发现是InputStream的原因,即一个InputStream流对象只能执行一次读取操作,当执行完读取操作之后再次执行已经无法读取出内容,这里由于是将读取一次的xml输入流再经过xsd验证,所以会报出如上的错误!

测试如下:

public void testInputStream() throws IOException {
    String test = "test inputStream";
    InputStream inputStream = new ByteArrayInputStream(test.getBytes());

    String str1 = IOUtils.toString(inputStream);
    System.out.println("first call : " + str1);

    String str2 = IOUtils.toString(inputStream);
    System.out.println("second call : " + str2);
}

执行结果如下:

1
这里写图片描述

从上面可以看出当第二次查询的时候输入流中已经没有数据了。如果想在第二次查询的时候仍然能够查出相同的内容,则需要使用reset()InputStream的指针移回到开始再进行读取,如下:

public void testInputStream() throws IOException {
    String test = "test inputStream";
    InputStream inputStream = new ByteArrayInputStream(test.getBytes());

    String str1 = IOUtils.toString(inputStream);
    System.out.println("first call : " + str1);

    inputStream.reset();

    String str2 = IOUtils.toString(inputStream);
    System.out.println("second call : " + str2);
}

2
这里写图片描述

可以看出已经能够读取和第一次相同的内容了!

从这个例子可以看出,其实InputStream就是一个字符序列,在读取的时候内部通过一个指针来指向要读取的数据,当读取完毕后,指针指向尾部,继续读取的时候不会读取新的数据,所以需要reset()将指针移动到开始,实际上reset()实际上是和mark()配合使用的。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值