验证失败后移动文件(Java) [英] Moving files after failed validation (Java)

查看:180
本文介绍了验证失败后移动文件(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在验证XML文件,根据验证结果,我们必须将文件移动到另一个文件夹中。

We are validating XML files and depending on the result of the validation we have to move the file into a different folder.

当XML有效时,验证器返回一个值,我们可以毫无问题地移动文件。当XML根据模式无效时也会发生同样的事情。

When the XML is valid the validator returns a value and we can move the file without a problem. Same thing happens when the XML is not valid according to the schema.

如果XML格式不正确,验证器会抛出异常,当我们尝试移动文件时, 它失败。我们相信在某个地方仍然有一个句柄可以保存文件。我们尝试在移动文件之前放置System.gc()并对问题进行排序,但我们不能将 System.gc()作为解决方案。

If however the XML is not well formed the validator throws an exception and when we try to move the file, it fails. We believe there is still a handle in the memory somewhere that keeps hold of the file. We tried putting System.gc() before moving the file and that sorted the problem but we can't have System.gc() as a solution.

代码如下所示。我们有一个File对象,我们从中创建一个StreamSource。然后将StreamSource传递给验证器。当XML格式不正确时,它会抛出SAXException。在异常处理中,我们使用.renameTo()方法移动文件。

The code looks like this. We have a File object from which we create a StreamSource. The StreamSource is then passed to the validator. When the XML is not well formed it throws a SAXException. In the exception handling we use the .renameTo() method to move the file.

sc = new StreamSource(xmlFile);
validator.validate(sc);

在捕获中我们尝试了

validator.reset();
validator=null;
sc=null;

但仍然 .renameTo()不是能够移动文件。如果我们在catch中放入 System.gc(),那么移动就会成功。

but still .renameTo() is not able to move the file. If we put System.gc() in the catch, the move will succeed.

有人可以告诉我如何不用 System.gc()进行排序?

Can someone enlight me how to sort this without System.gc()?

我们使用JAXP和saxon-9.1.0.8作为解析器。

We use JAXP and saxon-9.1.0.8 as the parser.

非常感谢

推荐答案

尝试创建一个 FileInputStream 并将其传递到 StreamSource ,然后在完成后关闭 FileInputStream 。通过传入文件,您已经无法控制关闭文件句柄的方式/时间。

Try creating a FileInputStream and passing that into StreamSource then close the FileInputStream when you're done. By passing in a File you have lost control of how/when to close the file handle.

这篇关于验证失败后移动文件(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆