当使用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);
}
执行结果如下:
从上面可以看出当第二次查询的时候输入流中已经没有数据了。如果想在第二次查询的时候仍然能够查出相同的内容,则需要使用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);
}
可以看出已经能够读取和第一次相同的内容了!
从这个例子可以看出,其实InputStream就是一个字符序列,在读取的时候内部通过一个指针来指向要读取的数据,当读取完毕后,指针指向尾部,继续读取的时候不会读取新的数据,所以需要reset()
将指针移动到开始,实际上reset()
实际上是和mark()
配合使用的。