Search code examples
javafileoutputstream

deleteOnExit not deleting file despite closing of stream writing to it


Relevant piece of code:

File tempFile = File.createTempFile("", "");
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
byte[] bytes = IOUtils.toByteArray(inputStream);
out.write(bytes);
out.close();

I'm running this as a local tomcat server run configuration via IntelliJ, and on quitting the server, it doesn't clean up the temp file. Any ideas on what I might be missing?


Solution

  • The File.deleteOnExit() installs a shutdown hook on the current VM so your delete is only triggered if the VM performs a normal controlled shutdown.

    For TOMCAT that would be via the bin\shutdown.bat or bin/shutdown.sh scripts within the TOMCAT installation.

    However if your TOMCAT server could be running for very long periods you should avoid calling File.deleteOnExit() altogether as the files to delete are stored in a List which could (eventually) grow to huge size and lead to OutOfMemoryError.

    This will not be a problem for a Tomcat instance that is re-started frequently, but would be an issue for high volume application server. If this different approach is needed, it is more reliable to keep track of temp files that are ready to delete in try...finally:

    File temp = null;
    try {
        ...
        temp = File.createTempFile("", "") ...
        ...
    } finally {
        deleteOnExit(temp);
    }
    
    private static void deleteOnExit(File fileToDelete)
    {
        if (fileToDelete != null)
            fileToDelete.delete();
    }