If you are using JDK 7 use the new Files.createTempDirectory class to create the temporary directory.
Before JDK 7 this should do it:
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);
}
You could make better exceptions (subclass IOException) if you want.
Do not use deleteOnExit() even if you explicitly delete it later.
Google 'deleteonexit is evil' for more info, but the gist of the problem is:
-
deleteOnExit() only deletes for normal JVM shutdowns, not crashes or killing the JVM process.
-
deleteOnExit() only deletes on JVM shutdown - not good for long-running server processes because:
-
The evilest of all - deleteOnExit() consumes memory for each temp file entry. If your process is running for months or creates a lot of temp files in a short time, you consume memory and never release it until the JVM shuts down.