Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving files after failed validation (Java)

Tags:

java

io

jaxp

saxon

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

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.

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.

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);

In the catch we tried

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

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

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

We use JAXP and saxon-9.1.0.8 as the parser.

Many thanks

like image 562
L4zl0w Avatar asked Jul 03 '26 08:07

L4zl0w


2 Answers

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.

like image 99
Mike Q Avatar answered Jul 04 '26 22:07

Mike Q


When you set sc = null, you are indicating to the garbage collector that the StreamSource file is no longer being used, and that it can be collected. Streams close themselves in their destroy() method, so if they are garbage collected, they will be closed, and therefore can be moved on a Windows system (you will not have this problem on a Unix system).

To solve the problem without manually invoking the GC, simply call sc.getInputStream().close() before sc = null. This is good practice anyway.

A common pattern is to do a try .. finally block around any file handle usage, eg.

try {
    sc = new StreamSource(xmlFile);
    // check stuff
} finally {
    sc.getInputStream().close();
}
// move to the appropriate place

In Java 7, you can instead use the new try with resources block.

like image 36
stefan Avatar answered Jul 04 '26 20:07

stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!