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?
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: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.