Deleting temporary directory
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开发者_如何学Go;
}
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:
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.
精彩评论