tags:

views:

4856

answers:

3

I have a test for a create DB method and I need a temp directory to put it in. The directory will be removed after the test is done. I tried using File.createTempFile(), like so:

tempDir = File.createTempFile("install", "dir");
tempDir.mkdir();

But tempDir is already exists as a file. How do I create a temp directory as opposed to a file?

+7  A: 

Well, "createTempFile" actually creates the file. So why not just delete it first, and then do the mkdir on it?

Paul Tomblin
You should always check the return value for mkdir(). If that is false then it means the directory already existed. This can cause security problems, so consider whether this should raise an error in your application or not.
sjbotha
+2  A: 

As discussed in this RFE and its comments, you could call tempDir.delete() first. Or you could use System.getProperty("java.io.tmpdir") and create a directory there. Either way, you should remember to call tempDir.deleteOnExit(), or the file won't be deleted after you're done.

Michael Myers
Isn't this property called "java.io.tmpdir", not "...temp"? See http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html
Andrew Swan
Quite so. I should have verified before repeating what I read.
Michael Myers
The java.io.tmpdir is shared so you need to do all the usual voodoo to avoid stepping on somebody elses toes.
Thorbjørn Ravn Andersen
+1  A: 

This code should work reasonably well:

public static File createTempDir() {
    final String baseTempPath = System.getProperty("java.io.tmpdir");

    Random rand = new Random();
    int randomInt = 1 + rand.nextInt();

    File tempDir = new File(baseTempPath + File.separator + "tempDir" + randomInt);
    if (tempDir.exists() == false) {
        tempDir.mkdir();
    }

    tempDir.deleteOnExit();

    return tempDir;
}
matt b
What if the directory already exists and you don't have read/write access to it or what if it's a regular file? You also have a race condition there.
Jeremy Huiskamp
Also, deleteOnExit will not delete non-empty directories.
trenton