问题
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));
}
}
回答1:
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:
FileInputStream fis = null;
try {
File f = new File(xmls.get(i));
File destFile = new File(structDir + "/badXMLs/" + f.getName());
fis = new FileInputStream(f);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(fis); // parse the FileInputStream, not the File
doc.getDoctype();
} catch (Exception e) {
if (fis != null) {
fis.close();
}
File f = new File(xmls.get(i));
File destFile = new File(structDir + "/badXMLs/" + f.getName());
System.out.println(f.getName());
delete = true;
}
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.
回答2:
Not sure about the answers that suggest you call close() on a file object since java.io.File has no such method, but I think they're headed in the right direction.
I'd suggest switching to using a FileInputStream and closing it.
the parse method can take either a File object or a FileInputStream so that should be ok.
来源:https://stackoverflow.com/questions/8714893/file-deletion-moving-failing