Search code examples
javajava-iofilewriter

File.delete doesn't delete file


In a unit test I create a file in the temp folder, after the tests I want to delete them.

 @After
    public void destroy() throws IOException {
        if (!new File(tempFile.toAbsolutePath().getParent().toString() + "\\file1.tmp").delete()) {
            System.out.println("file1.tmp not deleted");
        }
        if (!new File(tempFile.toAbsolutePath().getParent().toString() + "\\file2.log").delete()) {
            System.out.println("file2.log not deleted");
        }
        if (!new File(tempFile.toAbsolutePath().getParent().toString() + "\\file3.log").delete()) {
            System.out.println("file3.log not deleted");
        }
        if (!new File(tempFile.toAbsolutePath().getParent().toString() + "\\file4.log").delete()) {
            System.out.println("file4.log not deleted");
        }
    }

It deletes the files 1-3 without a single problem but I doensn't delete file4. Normally File.delete should throw an IOException but it just returns false.

I used the same method for each file, the writer is closed after creating and writing the files.

I hope I didn't forget any information


Solution

  • Normally File.delete should throw an IOException but it just returns false.

    Ahem ...

    File.delete does not throw an IOException if it fails to delete a file1. It returns false.

    As to why it is failing to delete the file, the most likely explanations are:

    • The file is locked because something has it open. Windows won't let you delete a file that is locked.

    • The application doesn't have the required (OS level) access to delete the file due; i.e. it is a file or directory permission issue.

    If you want to find out why the deletion is failing, the solution is to change your code to use Path and Files.delete(Path). The methods in Files are designed throw exceptions. In this case, the message should give the reason for the failure to delete.


    1 - The only exception that the method is documented as throwing is SecurityException which will only be thrown if there is a SecurityManager active.