Stephen D
Stephen D

Reputation: 3076

Cannot Delete File in try catch

I'll post my code first:

private void validateXml(String xml) throws BadSyntaxException{
    File xmlFile = new File(xml);
    try {
        JaxbCommon.unmarshalFile(xml, Gen.class);
    } catch (JAXBException jxe) {
        logger.error("JAXBException loading " + xml);
        String xmlPath = xmlFile.getAbsolutePath();
        System.out.println(xmlFile.delete()); // prints false, meaning cannot be deleted
        xmlFile.delete();
        throw new BadSyntaxException(xmlPath + "/package.xml");
    } catch (FileNotFoundException fne) {
        logger.error("FileNotFoundException loading " + xml + " not found");
        fne.printStackTrace();
    }
}

You can see in my comment where I print that the file cannot be deleted. Files can't be deleted from a try/catch? So, if there is a file with bad xml syntax, I want to delete the file in the catch.

EDIT: I can delete the file when I use delete() from outside of this function. I am on Windows.

Upvotes: 0

Views: 2277

Answers (3)

Crferreira
Crferreira

Reputation: 1238

There is no general restriction regarding the use of java.io.File.delete() on try/catch blocks.

The behavior of many java.io.File methods can depend on platform/enviroment that the application is running. It is because they can need to access file system resources.

For example, the following code returns false on Windows 7 and true on Ubuntu 12.04:

public static void main(String[] args) throws Exception {       
    File fileToBeDeleted = new File("test.txt");

    // just creates a simple file on the file system
    PrintWriter fout = new PrintWriter(fileToBeDeleted);

    fout.println("Hello");

    fout.close();

    // opens the created file and does not close it
    BufferedReader fin = new BufferedReader(new FileReader(fileToBeDeleted));

    fin.read();

    // try to delete the file
    System.out.println(fileToBeDeleted.delete());

    fin.close();
}

So, the real problem can depend on several factors. However, it is not related to the code residing on a try/catch block.

Maybe, the resource that you is trying to delete was opened and not closed or locked by another process.

Upvotes: 0

c.s.
c.s.

Reputation: 4816

Make sure that this method invocation JaxbCommon.unmarshalFile(xml, Gen.class); closes any stream when the exception occurs. If the stream that was reading the file is left opened then you cannot delete it.

Upvotes: 1

dkatzel
dkatzel

Reputation: 31648

The problem is unrelated to the try/catch. Do you have permissions to delete the file?

If you are using Java 7 you can use the Files.delete(Path) which I think will actually throw an IOException with the reason why you can't delete the file.

Upvotes: 0

Related Questions