In the code below I am trying to select xml files from an ArrayList xmls where xmls.get(i) is the absolute path of a file with extension .xml. If this file cannot be parsed by Document an exception is thrown and the file is moved to a different directory. However, I cannot move or delete the file although I can copy it to the directory destFile. The values of the last if statement return true for f.exists(), f.canRead(), f.canWrite(), f.canExecute but returns false forf.renameTo(destFile);
for(int i=0; i<xmls.size(); i++){
boolean delete = false;
try {
File f = new File(xmls.get(i));
File destFile = new File(structDir + "/badXMLs/" + f.getName());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
doc.getDoctype();
} catch (Exception e) {
File f = new File(xmls.get(i));
File destFile = new File(structDir + "/badXMLs/" + f.getName());
System.out.println(f.getName());
delete = true;
}
if(delete){
File f = new File(xmls.get(i));
File destFile = new File(structDir + "/badXMLs/" + f.getName());
System.out.println(f.exists());
System.out.println(f.canRead());
System.out.println(f.canWrite());
System.out.println(f.canExecute());
System.out.println(f.renameTo(destFile));
}
}
The default DocumentBuilder does not close the file when you get an Exception. The easiest way to avoid this is to use a FileInputStream, and close it yourself, like:
It doesn’t close it, so under windows at least, you can’t delete it or rename it. Note that you don’t need to create the DocumentBuilder each time either.