Goutham
Goutham

Reputation: 2859

How to delete a file after XML Parsing has thrown an error in java?

I have a piece of code that goes like this

File file = null;
try {

file = new file (filePath);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
// Do Stuff

} finally {

        if ( file.exists() ){
            file.delete();
        }
}

However if there is an error in the xml parsing, the file does not get deleted. Is there a way to fix this to ensure the file gets deleted?

Upvotes: 1

Views: 499

Answers (1)

I bet this is under Windows.

Under Windows you cannot delete an open file, and db.parse() opens the file for reading. Reconsider if you can pass in an InputStream which you are responsible for closing, and then you can delete the file.

Upvotes: 2

Related Questions