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,104
  • 17
  • 54
  • 62
Geo
  • 89,506
  • 114
  • 330
  • 511

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,402
  • 7
  • 58
  • 71
John Meagher
  • 21,568
  • 14
  • 51
  • 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
  • 28,703
  • 10
  • 67
  • 91
  • '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
  • 261,477
  • 36
  • 323
  • 432
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
  • 71,838
  • 15
  • 111
  • 127