Java Temp Directory Create createTempDir()

Here you can find the source of createTempDir()

Description

Guava's method, moved here to avoid a huge dependency TODO: maybe switch to JDK 7 to use its java.nio.file.Files#createTempDirectory()

License

Open Source License

Declaration

public static File createTempDir() 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

public class Main {
    private static final int TEMP_DIR_ATTEMPTS = 1000;

    /** Guava's method, moved here to avoid a huge dependency
     * TODO: maybe switch to JDK 7 to use its java.nio.file.Files#createTempDirectory()
     *//*from w w w  . java 2 s .c  o m*/
    public static File createTempDir() {
        return getTempDir(System.currentTimeMillis() + "");
    }

    public static File getTempDir(String name) {
        File baseDir = new File(System.getProperty("java.io.tmpdir"));
        String baseName = name + "-";
        for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
            File tempDir = new File(baseDir, baseName + counter);
            if (tempDir.isDirectory() || tempDir.mkdir())
                return tempDir;
        }

        throw new IllegalStateException("Failed to create directory within " + TEMP_DIR_ATTEMPTS
                + " attempts (tried " + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
    }
}

Related

  1. createTempDir()
  2. createTempDir(final String prefix)
  3. createTempDir(String prefix)
  4. createTempDir(String subdirectory)
  5. createTempDir(String suffix)