Deleting temporary directory

5.5k views Asked by At

I found some code on here for creating temporary directories in Java.

public static File createTempDirectory() throws IOException
{
    final File temp;
    temp = File.createTempFile("temp", Long.toString(System.nanoTime()));

    if(!(temp.delete()))
    {
        throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
    }
    if(!(temp.mkdir()))
    {
        throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
    }
    return temp;
}

How can I at the end of my servlet's life a handle on this temporary directory and delete it?

1

There are 1 answers

0
Joachim Sauer On BEST ANSWER

First:

Don't use this method of creating a temporary directory! It is unsafe! Use the Guava method Files.createTempDir() instead (or re-implement it manually, if you don't want to use Guava). The reason is described in its JavaDoc:

A common pitfall is to call createTempFile, delete the file and create a directory in its place, but this leads a race condition which can be exploited to create security vulnerabilities, especially when executable files are to be written into the directory.

Regarding your real question:

You need to delete the directory manually, which means you need to keep track of all directories you create (for example in a Collection<File>) and delete them when you know for sure that they are not longer needed.