我正在尝试针对JAVA中的XSD文件验证XML文件.我的问题不是验证本身,因为这可以正常工作.
我的问题是,验证后未释放XMLfile.如果以后尝试访问该文件,则会收到错误“该文件已被其他资源使用”.
仅当验证失败时才会发生此错误(validator.validate(xmlSource)抛出异常)
如果对该文件进行了验证而没有问题,则该文件将被释放并且可以被其他人访问.
有想法吗?
public void validateXMLAgainstXSD(String xmlPath, String xsdpath) throws ParserException, IOException
{
Source xmlSource = null;
File schemaFile = null;
SchemaFactory schemaFactory = null;
Schema schema = null;
Validator validator = null;
try
{
schemaFile = new File(xsdpath);
xmlSource = new StreamSource(new File(xmlPath));
schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schema = schemaFactory.newSchema(schemaFile);
validator = schema.newValidator();
validator.validate(xmlSource);
}
catch (SAXException e)
{
//_log.error("ParsingDataFile: XML file Could not be validated against XSD file: XML File=<", xmlFile.getAbsolutePath(), "> XSD file=<", xsdFile.getAbsolutePath(), ">. Exception=<", e, ">");
xmlSource = null;
schemaFile = null;
schemaFactory = null;
schema = null;
validator.reset();
validator = null;
//throw new ParserException(-1, ParserException.ERROR_CODE_XML_NOT_VALID, e);
}
}
解决方法:
我的建议是使用带有输入流的构造函数创建StreamSource.
像那样
InputStream inputStream = new FileInputStream(new File(xmlPath));
source = new StreamSource(inputStream);
然后在您的方法中使用finally语句
finally{
inputStream.close();
}
但是请记住,在最后阻止或关闭未初始化或未打开的inputStream引发的异常之前,请确保已初始化流.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。