Create a new and empty directory in the default temp directory using the given prefix in Java

Description

The following code shows how to create a new and empty directory in the default temp directory using the given prefix.

Example


//from  ww w.  j  a v  a  2 s. c om
/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2006.
 *
 * Licensed under the Aduna BSD-style license.
 */
import java.io.File;
import java.io.IOException;

public class Main {
  
  /**
   * Creates a new and empty directory in the default temp directory using the
   * given prefix. This methods uses {@link File#createTempFile} to create a
   * new tmp file, deletes it and creates a directory for it instead.
   * 
   * @param prefix The prefix string to be used in generating the diretory's
   * name; must be at least three characters long.
   * @return A newly-created empty directory.
   * @throws IOException If no directory could be created.
   */
  public static File createTempDir(String prefix)
    throws IOException
  {
    String tmpDirStr = System.getProperty("java.io.tmpdir");
    if (tmpDirStr == null) {
      throw new IOException(
        "System property 'java.io.tmpdir' does not specify a tmp dir");
    }
    
    File tmpDir = new File(tmpDirStr);
    if (!tmpDir.exists()) {
      boolean created = tmpDir.mkdirs();
      if (!created) {
        throw new IOException("Unable to create tmp dir " + tmpDir);
      }
    }
    
    File resultDir = null;
    int suffix = (int)System.currentTimeMillis();
    int failureCount = 0;
    do {
      resultDir = new File(tmpDir, prefix + suffix % 10000);
      suffix++;
      failureCount++;
    }
    while (resultDir.exists() && failureCount < 50);
    
    if (resultDir.exists()) {
      throw new IOException(failureCount + 
        " attempts to generate a non-existent directory name failed, giving up");
    }
    boolean created = resultDir.mkdir();
    if (!created) {
      throw new IOException("Failed to create tmp directory");
    }
    
    return resultDir;
  }

}




















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip