【问题标题】:XML validation does not release the xml fileXML 验证不释放 xml 文件
【发布时间】:2014-02-21 10:38:28
【问题描述】:

我正在尝试根据 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);
    }
  }

【问题讨论】:

  • 你如何'试图访问该文件之后'?
  • 你总是不得不关闭打开的资源或者大部分时间。我没有看到你使用任何 finally 块。
  • @LutzHorn 我尝试将文件从一个目录移动到另一个目录。但是 Rafik991 提供的方案解决了我的问题。
  • @Omoro 是的,如果我打开了任何东西,我需要关闭它。问题是,没有什么可以关闭的。但是 Rafik991 的解决方案解决了我的问题。

标签: java xml validation


【解决方案1】:

我的建议是使用带有输入流的构造函数来创建 StreamSource。

这样

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

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

finally{
inputStream.close();
}

但请记住,在进入 finally 阻塞或简单地捕获由关闭未初始化或打开的 inputStream 引发的异常之前,请确保初始化流。

【讨论】:

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

RMachnik 是对的,就像一个魅力!

也可以使用TryWithResources:

try (InputStream inputStream = new FileInputStream(file)) {
    ...
    new StreamSource(inputStream);
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多