9

Possible Duplicate:
Create a temporary directory in Java

Duplicate: stackoverflow.com/questions/375910

Is there a way of creating a temporary folder in java ? I know of File's static method createTempFile, but this will only give me a temporary file.

Craig Angus
  • 22,784
  • 18
  • 55
  • 63
Geo
  • 93,257
  • 117
  • 344
  • 520

4 Answers4

30

I've never seen a good solution for this, but this is how I've done it.

File temp = File.createTempFile("folder-name","");
temp.delete();
temp.mkdir();
Saeed Zarinfam
  • 9,818
  • 7
  • 59
  • 72
John Meagher
  • 22,808
  • 14
  • 54
  • 57
8

Any reason you can't use the directory defined by the java.io.tmpdir property?

ie

String dirName = System.getProperty("java.io.tmpdir");
cagcowboy
  • 30,012
  • 11
  • 69
  • 93
  • 'Temporary file' from createTempFile is automatically deleted when JVM exits. I think OP is asking for this kind of directory, so using existing tmpdir directory won't make it. (I needed something similar for writing unit tests, and used createTempFile+delete+mkdir and created only 'temporary' files within this directory -- JVM can then do the cleanup, if I remember correctly) – Peter Štibraný May 03 '09 at 17:17
  • 1
    Ok, it's not deleted automatically .. you need to ask JVM first to do so (by deleteOnExit) – Peter Štibraný May 03 '09 at 17:20
  • Just as a side note: you could easily add 'destruction on JVM exit' yourself by registering a shutdown hook. – Alexander Torstling Jul 22 '10 at 06:52
5

I would check out this past question in SO for a solution. Or this one!

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
4

I write my own utility classes for creating temporary directories and for disposing them when they are not anymore needed. For example like this.

Esko Luontola
  • 73,184
  • 17
  • 117
  • 128