2014-02-21 57 views
0

我想验证一个XML文件在JAVA中的XSD文件。我的问题不是验证本身,因为这工作正常。 我的问题是,验证后XML文件未发布。如果之后尝试访问该文件,则会出现错误“该文件被其他资源使用”。XML验证不会释放xml文件

只有在验证失败时才会发生此错误(从validator.validate(xmlSource); troll发出异常;) 如果该文件没有问题进行验证,则该文件被释放并且可被其他人访问。

任何想法?

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); 
    } 
    } 
+0

你是如何'试图访问文件'? – 2014-02-21 10:48:22

+0

您总是必须关闭已打开的资源或大部分时间。我没有看到你使用任何'finally'块。 – Omoro

+0

@LutzHorn我尝试将文件从一个目录移动到另一个目录。但Rafik991提供的解决方案解决了我的问题。 –

回答

0

我的建议是使用inputstream使用构造函数创建StreamSource。

InputStream inputStream = new FileInputStream(new File(xmlPath)); 
    source = new StreamSource(inputStream); 

,然后在你的方法使用finally语句

finally{ 
inputStream.close(); 
} 

但请记住,以确保你你去finally块或简单地赶上异常通过抛出之前初始化流关闭未初始化或打开inputStream。

+0

当你用“new File”构造函数调用处理器时,处理器应该关闭这个流,但是看起来好像它没有这样做。这个建议可能会提供解决方法。但是我会将一个SystemId添加到StreamSource构造函数中,以便知道文档的基本URI。 –

+0

谢谢@ Rafik991。这解决了我的问题! –

+0

不客气! ;) – RMachnik