Issue
I am developing a function that is dedicated to reading XML files. When the reading is correct, the function will move the file to a folder called success, otherwise it will move it to a so-called error. The fact is that, when the file comes well, the function does its job correctly, while when it fails to read it because the file is wrong throws me the following exception:
java.nio.file.FileSystemException: c:\inbox\TEST.XML -> c:\error\TEST.XML: The process cannot access the file because it is being used by another process.
This is the code:
private void start(){
//Some stuff
boolean ok = true;
try{
readXml(file.getPath());
} catch(XmlParserException xmle){
log.error("Error");
ok = false;
} finally {
moveFiles(ok, file);
}
}
private void moveFiles(boolean parseOk, File file){
//Set path with success or error folder
String path = parseoOk ? (String) mainProperties.get(Constants.SUCCESS)
: (String) mainProperties.get(Constants.ERROR);
File fileTo = new File(path + Constants.ROUTE_SLASH + file.getName());
try {
Files.move(file.toPath(), fileTo .toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (FileSystemException fse) {
log.error("In Use");
log.error(fse.getMessage());
} catch (IOException e) {
log.error("IOERROR");
log.error(e.getMessage());
}
}
private void readXml(String rutaFichero) throws XmlParserException{
DocumentBuilder documentBuilder = initializeDocumentBuilder();
try {
File archivo = new File(rutaFichero);
Document documento = documentBuilder.parse(archivo); //Fails here
//Do some stuff
} catch(XPathExpressionException | DOMException | SAXException | IOException | ParseException e1){
throw new XmlParserException("Error when parsing XML: " + e1);
}
}
Solution
Check whether you have any un-closed file read/write operations for the xml file. If you haven't, maybe documentBuilder.parse(archivo)
isn't closing streams it opens. You may be able to verify this with switch to FileInputStream
:
File archivo = new File(rutaFichero);
try (InputStream in = new FileInputStream(archivo)) {
Document documento = documentBuilder.parse(in);
// ...
} catch(XPathExpressionException | DOMException | SAXException | IOException | ParseException e1){
throw new XmlParserException("Error when parsing XML: " + e1);
}
UPDATE
A not-closed File
after XML parse issue appears in JDK bug database a few times for SAX + DOM, see the DocumentBuilder.parse(File)
issue JDK-8151585. The code I've proposed above is a good workaround to this bug.
Answered By - DuncG
Answer Checked By - Willingham (JavaFixing Volunteer)