In my application, I'm checking a value in the xml file, say some.xml
and moving the file to another directory depending on the outcome of this read.
When some.xml
is malformed, SaxBuilder
is throwing the JDOMException
, but not releasing the file. When i attempt to move some.xml
after that, i'm getting the error that some.xml
is used by another process.
my code is this (irrelevant details removed):
private static String getName(Path fullPath) {
File f = fullPath.toFile();
SAXBuilder saxBuilder = new SAXBuilder();
Document doc = null;
String result = "";
try {
doc = saxBuilder.build(f);
result = doc.getRootElement().getChild("imageControl").getText();
} catch (JDOMException | IOException e) {
e.printStackTrace();
}
return result;
}
so - after running this, on a malinformed xml passed in, that malinformed xml file is still open by the SaxBulider-- can't move it in my subsequent method.
How to fix this?
the only i can think of right now is to make a temporary copy of the xml and make the above reading on taht copy. but this is nowhere near the best thing.
I'm using JDOM 2.0.6 on Java 1.7
TIA.
//-----------------------------
EDIT:
the following fix in the corresponding lines didn't make it:
try (InputStream is = new FileInputStream(f)){
doc = saxBuilder.build(f);
the problem is definitely in this method. it's all running the expected way when I comment out its call.
//-----------------------------------------------
EDIT-2
nope - the typo.
try (InputStream is = new FileInputStream(f)){
doc = saxBuilder.build(is);
works.
It seems that SaxBuilder does not close resources, so please try to use build(InputStream)
or build(Reader)
methods instead and close stream/reader in finally block explicitly.
I would agree with @Jim Garrison, that JDOM probably forgets to close the input in case of an exception.